49 Commits

Author SHA1 Message Date
Zayden-Jung dd8b41b67e Merge pull request '统一 Bedrock 启动入口并将 db 重命名为 database' (#28) from codex/sql-persistence into main
Deploy Rust Bedrock / deploy (push) Has started running
Reviewed-on: #28
Reviewed-by: Zayden-Jung <zayden.jung@entroia.com>
2026-11-30 13:44:31 +00:00
codex-bot f0470c406b Rename the db crate to database 2026-11-30 20:23:47 +08:00
codex-bot af9f25baa5 Move storage initialization into the backend executable 2026-11-30 20:23:23 +08:00
Zayden-Jung 66be7099ec Merge pull request '将 Bedrock 存储切换为数据库原生驱动' (#25) from codex/sql-persistence into main
Deploy Rust Bedrock / deploy (push) Failing after 30m4s
Reviewed-on: #25
Reviewed-by: Zayden-Jung <zayden.jung@entroia.com>
2026-11-30 12:19:11 +00:00
codex-bot 1775943d79 Group release script steps in deployment diagrams 2026-11-30 20:16:54 +08:00
codex-bot 01023404be Show a separate flow for each deployment method 2026-11-30 20:13:51 +08:00
codex-bot df2fff7a80 Merge main into SQL persistence and integrate backend configuration 2026-11-30 19:19:27 +08:00
Zayden-Jung 3eebf55112 Merge pull request '在单个 Axum 进程提供 Bedrock 业务与管理 API' (#26) from codex/backend-admin-architecture into main
Deploy Rust Bedrock / deploy (push) Has been cancelled
Reviewed-on: #26
Reviewed-by: Zayden-Jung <zayden.jung@entroia.com>
2026-11-30 11:00:11 +00:00
Zayden-Jung 1b10181cf1 Merge pull request '添加工作区文档模型和 SQL 存储适配' (#27) from codex/document-model into main
Deploy Rust Bedrock / deploy (push) Failing after 30m4s
Reviewed-on: #27
Reviewed-by: Zayden-Jung <zayden.jung@entroia.com>
2026-11-30 10:59:40 +00:00
codex-bot 66b6910eb1 Keep context implementations with their document models 2026-11-30 18:56:28 +08:00
codex-bot 8707eb87b6 Share address and TLS types across backend configurations 2026-11-30 18:39:52 +08:00
codex-bot 455a3580d6 Model pages and blocks as document nodes 2026-11-30 18:36:16 +08:00
codex-bot 69513d9ffb Group deployment files by deployment method 2026-11-30 18:27:11 +08:00
codex-bot 9869a9966c Unify backend resources and role bindings in clusters 2026-11-30 18:24:24 +08:00
codex-bot 6469d3aad6 Serve business and admin routes from one backend process 2026-11-30 18:24:21 +08:00
codex-bot 365be3870e Model workspaces, users, and organizations 2026-11-30 18:19:05 +08:00
codex-bot ac62c8a655 Name SQL cluster configuration explicitly 2026-11-30 18:05:01 +08:00
codex-bot 296fb9b1b7 Add initial Axum application and admin backends 2026-11-30 18:02:10 +08:00
codex-bot 3c551ca0a3 Define all cluster drivers in the driver module 2026-11-30 17:59:32 +08:00
codex-bot deb535c256 Shorten the SQL document adapter module name 2026-11-30 17:48:50 +08:00
codex-bot 353ea1558c Stack deployment and SQL check diagrams vertically 2026-11-30 17:43:15 +08:00
codex-bot b64a88011f Add a workspace document model and SQL storage adapter 2026-11-30 17:41:20 +08:00
codex-bot 3d0ce4ad7d Document deployment and SQL checks with Mermaid 2026-11-30 17:34:40 +08:00
codex-bot 73192bf944 Document clusters module dependencies 2026-11-30 17:24:36 +08:00
codex-bot 51beaafc4c Explain Serde derives on backend driver enums 2026-11-30 17:19:28 +08:00
codex-bot 7982fffcda Add a versioned backend catalog and YAML deployment configuration 2026-11-30 17:11:03 +08:00
codex-bot c270adbab4 Print the inner string in Address debug output 2026-11-30 07:37:02 +08:00
codex-bot 9f3848199d Use native drivers for Bedrock SQL storage 2026-11-30 07:02:20 +08:00
Zayden-Jung 698f126033 Merge pull request '实现 Bedrock SQL 存储与部署配置' (#24) from codex/sql-persistence into main
Deploy Rust Bedrock / deploy (push) Failing after 31m4s
Reviewed-on: #24
Reviewed-by: Zayden-Jung <zayden.jung@entroia.com>
2026-11-29 20:47:50 +00:00
codex-bot c98b694a70 Name the shared database module common 2026-11-30 04:40:53 +08:00
codex-bot 6c51e68817 Separate shared database implementation from crate exports 2026-11-30 04:35:54 +08:00
codex-bot 81b70f0046 Rename the database crate to db 2026-11-30 04:09:40 +08:00
codex-bot 6b34a11dbb Rename the SQL storage crate to sql 2026-11-30 04:00:38 +08:00
codex-bot 36184b07a0 Move SQL connection routing into sql_storage 2026-11-30 03:50:39 +08:00
codex-bot bb15a7043c Name the SQL document storage crate sql_storage 2026-11-30 03:47:24 +08:00
codex-bot 2f2a39621c Consolidate SQL backends into persistence modules 2026-11-30 03:43:47 +08:00
codex-bot 55d66d5d9b Embed the deployment flow in deployment and CI docs 2026-11-30 01:17:13 +08:00
codex-bot d31cd5615e Move cluster configuration test to integration tests 2026-11-30 00:53:05 +08:00
codex-bot 351cc156dd Deploy Rust Bedrock from main on the existing host 2026-11-30 00:51:35 +08:00
codex-bot a01bac3a48 Pause automated SQL verification 2026-11-30 00:48:59 +08:00
codex-bot 632c3a8882 Scope SQL verification to main PRs and render deployment configuration
Bedrock SQL storage / sql (pull_request) Has been cancelled
2026-11-30 00:26:15 +08:00
codex-bot 807a02e081 Implement Bedrock SQL persistence backends
Bedrock SQL storage / sql (push) Successful in 23m11s
2026-11-30 00:23:48 +08:00
Zayden-Jung 0c34703ec7 Merge pull request '将 Bedrock 主线切换为 Rust 初始项目 [skip ci]' (#23) from codex/bedrock-rust into main
Reviewed-on: #23
2026-11-29 15:35:46 +00:00
codex-bot 59f2ef1bf2 Replace legacy Go project with Rust Bedrock bootstrap 2026-11-29 23:33:11 +08:00
Zayden-Jung fa79b1e6ce Merge pull request '将共享后端改名为 Bedrock [skip ci]' (#22) from codex/bedrock-rename into main
Reviewed-on: #22
2026-11-19 11:44:44 +00:00
codex-bot 6fcfbf1def Rename shared backend to Bedrock [skip ci] 2026-11-19 19:30:05 +08:00
codex-bot 3bc3051383 Merge PR #21: 补充 Foundry 入口注册与部署注释 [skip ci] 2026-11-19 11:20:45 +00:00
codex-bot 53bc8d73eb docs: explain deployment stages and separate comment sections [skip ci] 2026-11-17 00:01:26 +08:00
codex-bot 00fd89af1a docs: explain Foundry HTTP module registration [skip ci] 2026-11-16 21:18:25 +08:00
186 changed files with 6699 additions and 23943 deletions
-30
View File
@@ -1,30 +0,0 @@
# 示例值供部署配置参考,真实 .env/凭据不得提交。公共地址必须是 HTTPS 根 origin。
PUBLIC_ORIGIN=https://api.example.com
DATABASE_URL=postgresql://foundry:replace-me@postgres.internal:5432/foundry_auth
GOOGLE_CLIENT_ID=replace-me.apps.googleusercontent.com
GOOGLE_CLIENT_SECRET=replace-me
# 项目→固定前端回调白名单;生产 HTTPS,开发仅允许回环 HTTP,不能由请求任意指定。
FOUNDRY_PROJECTS='{"notes":"http://localhost:3000/auth/callback","board":"http://localhost:3001/auth/callback"}'
# 默认监听回环,容器发布时 release.sh 显式改为 0.0.0.0;PORT 仅决定内部 HTTP 监听。
HOST=127.0.0.1
PORT=8080
# Optional email verification through TLS SMTP.
# 邮件配置整组缺省可关闭,部分填写会启动失败;此示例只接受隐式 TLS 465。
SMTP_HOST=smtpdm.aliyun.com
SMTP_PORT=465
SMTP_USERNAME=noreply@notice.entroia.com
SMTP_PASSWORD=replace-me
SMTP_FROM=noreply@notice.entroia.com
# Optional Sign in with Slack.
# Slack 客户端 ID 与 Secret 必须成对配置,回调 URL 由 PUBLIC_ORIGIN 派生。
SLACK_CLIENT_ID=replace-me
SLACK_CLIENT_SECRET=replace-me
# Optional shared paper corpus; enable only after PostgreSQL publication.
# Store the real read-only connection string in the protected server research.env.
FOUNDRY_RESEARCH_DATABASE_URL=
FOUNDRY_RESEARCH_SCHEMA=research
# Deployment migration container; independent of database/schema names.
FOUNDRY_POSTGRES_CONTAINER=foundry-postgres
-106
View File
@@ -1,106 +0,0 @@
# 分支推送和 PR 检查:格式/编译、隔离数据库回归、固定版本 headless 客户端以及 HTTP smoke。
name: Foundry Go checks
on: [push, pull_request]
jobs:
check:
# 所有构建在此远程 runner 执行;脚本中的 Docker 挂载路径也基于它的工作区。
runs-on: ces-control
# Cold toolchain installation can exceed ten minutes on the existing runner.
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version-file: go.mod
cache: false
- name: Check formatting, test and build
run: |
set -eu
test -z "$(gofmt -l cmd internal)"
go test -mod=readonly ./...
go build -mod=readonly -o bin/foundry ./cmd/foundry
# 仅 push 可使用已配置秘密做占位码探测,不能替代真实用户 OAuth 登录。
- name: Check Slack OAuth configuration and endpoint
if: gitea.event_name == 'push'
env:
SLACK_CLIENT_ID: ${{ secrets.SLACK_CLIENT_ID }}
SLACK_CLIENT_SECRET: ${{ secrets.SLACK_CLIENT_SECRET }}
run: |
python3 - <<'PYSLACK'
import json, os, secrets, sys, urllib.parse, urllib.request
client = os.environ.get("SLACK_CLIENT_ID", "")
secret = os.environ.get("SLACK_CLIENT_SECRET", "")
if not client and not secret:
print("Slack client verification skipped because credentials are not configured")
sys.exit(0)
if not client or not secret:
sys.exit("Both Slack client secrets must be configured")
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *args, **kwargs):
return None
opener = urllib.request.build_opener(NoRedirect)
code = "foundry-invalid-preflight-" + secrets.token_hex(16)
def probe(password):
body = urllib.parse.urlencode({
"client_id": client, "client_secret": password,
"code": code, "grant_type": "authorization_code",
"redirect_uri": "https://api.foundry.entroia.com/auth/slack/callback"
}).encode()
request = urllib.request.Request(
"https://slack.com/api/openid.connect.token", data=body,
headers={"Content-Type": "application/x-www-form-urlencoded"})
with opener.open(request, timeout=20) as response:
result = json.load(response)
return result.get("error", "")
try:
actual = probe(secret)
control = probe(secrets.token_hex(32))
except Exception as error:
sys.exit("Slack preflight request failed (" + type(error).__name__ + ")")
if actual in ("invalid_code", "invalid_grant") and control in ("bad_client_secret", "invalid_client"):
print("Slack client credentials accepted; invalid-secret negative control rejected")
print("A real user authorization is still required to verify the complete login")
elif actual in ("invalid_code", "invalid_grant") and control in ("invalid_code", "invalid_grant"):
print("Both Slack Actions secrets are available and the OAuth endpoint is reachable")
print("Slack rejected the placeholder code before validating the client secret")
print("Client-secret validity requires a real user authorization; this is not a complete login test")
else:
known = {"invalid_client_id", "bad_client_secret", "invalid_client", "invalid_code",
"invalid_grant", "bad_redirect_uri", "accesslimited", "ratelimited"}
print("Configured credential result:", actual if actual in known else "unclassified")
print("Negative control result:", control if control in known else "unclassified")
sys.exit("Slack client preflight could not verify the configured credentials")
PYSLACK
# 固定客户端提交避免服务端回归随外部默认分支漂移,下载不使用用户本机凭据。
- name: Fetch pinned headless HTTP integration client
env:
HEADLESS_CLIENT_REVISION: dcbbdad25de7c3b1d6bee317df6074da2c0642eb
run: |
set -eu
mkdir -p .headless-client
curl --fail --silent --show-error --location \
"https://gitea.entroia.com/Zayden-Jung/Endoleap/archive/$HEADLESS_CLIENT_REVISION.tar.gz" \
| tar -xz --strip-components=1 -C .headless-client
test -f .headless-client/tests/headless/foundry.integration.mjs
printf 'Pinned Endoleap client: %s\n' "$HEADLESS_CLIENT_REVISION"
- name: Verify schema migration and real headless HTTP client in an isolated database
run: HEADLESS_CLIENT_SOURCE="$PWD/.headless-client" bash deploy/check-schema.sh
# smoke 不依赖可连接数据库:healthz 只检查进程,缺 bearer 的 me 必须先返回 401。
- name: Smoke test HTTP routes
env:
PUBLIC_ORIGIN: https://api.example.com
DATABASE_URL: postgres://foundry:fixture@127.0.0.1:5432/foundry
FOUNDRY_RESEARCH_DATABASE_URL: ''
GOOGLE_CLIENT_ID: fixture
GOOGLE_CLIENT_SECRET: fixture
FOUNDRY_PROJECTS: '{"notes":"http://localhost:3000/auth/callback"}'
PORT: '18080'
run: |
set -eu
./bin/foundry &
server_pid=$!
trap 'kill "$server_pid" 2>/dev/null || true' EXIT
curl --silent --show-error --fail --retry 5 --retry-connrefused http://127.0.0.1:18080/healthz
status=$(curl --silent --show-error -o /dev/null -w '%{http_code}' http://127.0.0.1:18080/projects/notes/auth/me)
test "$status" = 401
+14 -32
View File
@@ -1,47 +1,29 @@
# 仅 main 的相关路径变更触发发布;工作分支验证不应运行此生产切换。 name: Deploy Rust Bedrock
name: Deploy Foundry Core
on: on:
push: push:
branches: [main] branches: [main]
paths:
- 'cmd/**'
- 'internal/**'
- 'go.mod'
- 'go.sum'
- 'deploy/**'
- 'db/**'
- '.gitea/workflows/deploy.yml'
# 发布串行排队且不取消正在进行的路由/数据库操作。
concurrency: concurrency:
group: foundry-core-main-deploy group: bedrock-rust-deploy
cancel-in-progress: false cancel-in-progress: false
jobs: jobs:
deploy: deploy:
if: gitea.ref == 'refs/heads/main' && gitea.event_name == 'push' if: gitea.ref == 'refs/heads/main' && gitea.event_name == 'push'
runs-on: ces-control runs-on: ces-control
timeout-minutes: 15 timeout-minutes: 30
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: actions/setup-go@v5
with: with:
go-version-file: go.mod persist-credentials: false
cache: false - name: Build the Rust release
# 在远程 runner 生成无 CGO 二进制,供只读 slim 容器执行。 run: bash deploy/gitea/build-release.sh
- name: Verify and build - name: Publish and initialize Bedrock storage
run: |
set -eu
test -z "$(gofmt -l cmd internal)"
go test -mod=readonly ./...
CGO_ENABLED=0 go build -mod=readonly -o bin/foundry ./cmd/foundry
# secrets 仅注入进程环境,项目/引导 JSON 来自 Actions Variables,release 再检查内容。
- name: Deploy and verify backend readiness
env: env:
GOOGLE_CLIENT_ID: ${{ secrets.GOOGLE_CLIENT_ID }} BEDROCK_PG_HOST: ${{ vars.BEDROCK_PG_HOST }}
GOOGLE_CLIENT_SECRET: ${{ secrets.GOOGLE_CLIENT_SECRET }} BEDROCK_PG_PORT: ${{ vars.BEDROCK_PG_PORT }}
SLACK_CLIENT_ID: ${{ secrets.SLACK_CLIENT_ID }} BEDROCK_PG_DATABASE: ${{ vars.BEDROCK_PG_DATABASE }}
SLACK_CLIENT_SECRET: ${{ secrets.SLACK_CLIENT_SECRET }} BEDROCK_PG_USER: ${{ vars.BEDROCK_PG_USER }}
FOUNDRY_PROJECTS: ${{ vars.FOUNDRY_PROJECTS }} BEDROCK_PG_PASSWORD: ${{ secrets.BEDROCK_PG_PASSWORD }}
FOUNDRY_ONBOARDING: ${{ vars.FOUNDRY_ONBOARDING }} run: bash deploy/gitea/release.sh target/bedrock-release/bedrock "$GITHUB_SHA"
run: bash deploy/release.sh bin/foundry
+3 -4
View File
@@ -1,4 +1,3 @@
# 本地配置可能含凭据,构建/文档生成目录不作为源码提交。 /target
.env /bedrock.sqlite3
/bin/ /bedrock.sqlite3-*
/api-docs/
Generated
+2512
View File
File diff suppressed because it is too large Load Diff
+31
View File
@@ -0,0 +1,31 @@
[workspace]
members = ["crates/*"]
resolver = "3"
[workspace.package]
edition = "2024"
rust-version = "1.91"
[workspace.dependencies]
axum = { version = "0.8", default-features = false, features = ["http1", "json", "tokio"] }
clusters = { path = "crates/clusters" }
database = { path = "crates/database" }
documents = { path = "crates/documents" }
deadpool-postgres = "0.14.1"
mysql_async = { version = "0.36.1", default-features = false, features = ["minimal-rust", "ring", "rustls-tls", "tls12"] }
rusqlite = { version = "0.32.1", features = ["bundled"] }
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
rustls-pemfile = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
serde-saphyr = { version = "2.2", default-features = false, features = ["deserialize", "serialize"] }
subtle = "2"
tempfile = "3"
toml = "0.9"
thiserror = "2"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
tokio-postgres = "0.7.18"
tokio-postgres-rustls = { version = "0.13", default-features = false }
tokio-rusqlite = "0.6"
url = "2"
webpki-roots = "1"
+31 -626
View File
@@ -1,642 +1,47 @@
# 造物工坊 · Foundry Core # Bedrock storage
共享后端的第一版提供 Google 登录。各项目通过同一个 HTTPS API 登录,在私有 PostgreSQL 的认证库中维护独立账号和会话。项目业务库可分别配置独立的数据库和角色。 Bedrock stores JSON documents in SQLite, PostgreSQL or MySQL. Each backend has its own module in the `database` crate. SQLite is the default and creates `bedrock.sqlite3` in the current directory on first start.
## 服务端配置 ## Storage boundaries
1. 在 Google Cloud 创建一个 Web application OAuth 客户端。授权重定向 URI 填写 `https://<API 域名>/auth/google/callback`。所有项目信任同一个客户端,因此共享 Google 同意页面的应用名称。 `database` owns the transactional document data, revisions, and snapshots used by the application. `clusters` resolves deployment settings. The `database` connection module selects the SQL driver and read endpoints. The backend modules share document types, validation, and encoding in `common.rs`.
2. 在服务器私网准备 PostgreSQL 13 或以上版本。在认证库执行一次 `db/001-auth.sql`(使用 `psql -v ON_ERROR_STOP=1`),给运行账号授予这四张表所需的查询及增删改权限。
3. 按 `.env.example` 注入运行环境变量。每个项目配置一个固定的前端回调地址,本地开发可用 localhost。将 Google 客户端密钥和数据库连接串存入服务器的密钥管理设施。
4. 由 Gitea Actions 在 `ces-control` 上使用 Go 1.25 构建并检查。部署工作流仅处理 `main` 上影响后端或部署的改动,将二进制启动在服务器 Docker 私网,由 Traefik 提供 HTTPS。通过 `GET /healthz` 检查进程,通过 `GET /readyz` 检查认证库。
5. 代理避免记录 Google 回调的查询参数及认证请求头。设置入口限流,并定时删除三张临时表(`oauth_attempts`、`login_grants`、`project_sessions`)中 `expires_at <= now()` 的记录。
## 共享论文库(Thesisly) Notion describes sharding online PostgreSQL block data by workspace and feeding a downstream S3 data lake from PostgreSQL changes. Bedrock supports named SQL roles and read replicas. The catalog can describe S3 buckets. Object I/O, workspace routing, and data-lake ingestion are future work. [Notion's PostgreSQL sharding](https://www.notion.com/blog/sharding-postgres-at-notion) · [Notion's data lake](https://www.notion.com/blog/building-and-scaling-notions-data-lake)
可选只读接入见[共享论文 API](docs/research-api.md)。Thesisly 使用同一后端的 `/projects/{project}/research/papers` 列表、搜索和详情;只有配置服务器上的 `FOUNDRY_RESEARCH_DATABASE_URL` 时才启用。连接串保存在受保护的 `research.env`,不放入前端或 Actions Variables。当前仍等待 Paper Atlas 全量 PostgreSQL 迁移完成及真实数据验收,尚未启用线上论文接口。 ## Web backend
## Actions 部署配置 Run the Axum service with `cargo run --locked -p backend`. One process owns
the database connection, loads one deployment configuration, and serves
separate routers on the business and optional admin listeners.
在仓库的 Actions Secrets 配置 `GOOGLE_CLIENT_ID` 和 `GOOGLE_CLIENT_SECRET`,在 Actions Variables 配置 `FOUNDRY_PROJECTS`。变量值为 JSON 对象,例如 `{"prompt":"http://localhost:17321/auth/callback"}`。部署读取服务器上预先配置的 `/opt/endoleap-infra/foundry/database.env`,OAuth 值由 Actions 在启动容器时注入。 | Listener | Setting and default | Routes |
|---|---|---|
| Business | `BEDROCK_BACKEND_LISTEN`, default `127.0.0.1:8080` | `GET /healthz`, `GET /readyz` |
| Admin | `BEDROCK_ADMIN_LISTEN`, default `127.0.0.1:8081` when enabled | `GET /healthz`, `GET /readyz`, `GET /admin/v1/status` |
Google OAuth 的授权回调地址为 `https://api.foundry.entroia.com/auth/google/callback`。工作流会验证数据库就绪、匿名请求返回 401 和 HTTPS 就绪。前端接入后,可在浏览器用 Google 测试账号验证完整登录、回调、兑换和会话。 The business readiness probe checks access to the current deployment revision.
Set `BEDROCK_ADMIN_TOKEN` from a private credential source to enable the admin
listener. Send it as `Authorization: Bearer <token>` for the status endpoint.
Keep the admin listener on loopback or behind an internal TLS endpoint.
## 前端接入 The `admin_backend` library reports the deployment, storage driver, read-only
mode, and the loaded configuration version for the instance that served the
request. `BEDROCK_CONFIG_VERSION` can override the reported version label. The
admin router reads the same resolved configuration the process used to open the
database. Give every replica the same config file and version label through your
deployment process. Run `cargo run --locked -p backend -- --init-storage` for one-shot storage
initialization. The release process uses the same mode.
1. 在浏览器用 Web Crypto 生成 32 字节随机值,编码为无填充 Base64URL,作为 verifier 暂存在当前 tab 的 sessionStorage。对 verifier 字符串做 SHA-256 并用相同编码得到 challenge。 ## Database configuration
2. 顶层导航到 `GET /projects/<project>/auth/google?challenge=<challenge>`。Google 回到共享 API 后,API 将浏览器重定向至已配置的项目回调。
3. 回调页从 URL fragment 读取 `code` 或 `error`,用 history.replaceState 清掉 fragment。收到 code 时,向 `POST /projects/<project>/auth/exchange` 发送 `X-Foundry-Code` 和 `X-Foundry-Verifier` 请求头,随后清理暂存的 verifier。code 有效期一分钟,仅可使用一次。
4. 将返回的八小时会话凭证保存在内存中,使用 `Authorization: Bearer <access_token>` 调用 `GET /projects/<project>/auth/me`。通过 `POST /projects/<project>/auth/logout` 撤销会话并清理本地凭证。刷新页面后,内存凭证需要通过重新登录获取。
同一个 Google 账号首次进入不同项目时,会分别创建用户 ID。会话绑定其签发项目。Google 账号的标识 `sub` 用于认领同一项目的既有账号,邮箱只作为资料字段。当前注册模式为开放注册。 Set `BEDROCK_DB_CONFIG` to a private YAML deployment configuration. See the [multi-storage example](deploy/kubernetes/multi-storage.yaml). TOML and existing JSON files also load through the same configuration model.
## 验收 `resources` lists named backends, each with a `kind` and its own settings. `bindings` maps roles such as `documents` or `attachments` to those resources. The executable logs the configuration version and initializes bound SQL resources at startup. Existing `cluster`, `clusters`, `sql`, `object_storage`, and `sqlite_path` inputs are migrated to this shape when loaded.
用同一个 Google 测试账号分别登录两个项目,确认用户 ID 不同。用 A 的会话请求 B 的 `me` 应返回 401。验证兑换码重放被拒绝,并确认退出 A 后 B 的会话仍有效。 The database must already exist for PostgreSQL and MySQL. Bedrock creates its own tables and deployment row on a writable startup. Network endpoints use TLS with certificate and hostname verification by default. For a private test database without TLS, set the SQL resource's `tls` to `"disabled"`. A top-level `"read_only": true` opens an existing deployment without initializing it. For SQLite, set the resource's `primary` to the file path.
## Runtime HTTPS trust Applications use `database::connect` for the documents role or `database::connect_sql` for an explicitly resolved SQL role. A write batch commits at one new revision if its expected deployment revision still matches. Reads can target the primary or prefer replicas. Use an explicit revision to require that snapshot and fall back when replicas have fallen behind. A tombstone removes a document from subsequent snapshots while preserving earlier revisions. JSON null remains a stored value.
The Go backend needs an operating-system CA bundle for Google and Slack HTTPS For MySQL, use `Connection::mysql_writer` to acquire, renew or release a writer lease. An active lease blocks ordinary writes. Use `commit_with_lease` while holding it. `delete_deployment` requires an active lease, deletes that deployment's documents and permanently retires its ID in the database.
requests. The `node:24-bookworm-slim` runtime does not include that trust store;
Node's own successful HTTPS checks do not validate Go's trust configuration.
`deploy/release.sh` mounts the deployment host's
`/etc/ssl/certs/ca-certificates.crt` read-only and sets `SSL_CERT_FILE` to that
path. The deployment fails before switching traffic if the host bundle is
missing or unreadable in the candidate. Keep TLS certificate verification
enabled and maintain the deployment host's trusted CA package.
## Codex execution See [deployment configuration](deploy/README.md) for the PostgreSQL configuration renderer and deployment-only variables.
When enabled, `POST /projects/{project}/codex/exec` accepts a JSON object
containing only a nonempty `prompt` string and returns `{"result":"…"}`.
Use `Authorization: Bearer <token>` with a dedicated 32-byte random token
encoded as 64 hex characters. Ordinary OAuth sessions cannot execute Codex.
Missing, unknown and revoked tokens return 401. A valid token for a different
project returns 403. Requests are limited to 32 KiB, CLI output to 512 KiB,
and each execution to 90 seconds. The worker accepts one execution at a time
and returns 429 when busy.
On the deployment host, provision `/opt/endoleap-infra/foundry/codex` with:
- `grants/projects.json` containing a JSON object mapping lowercase hex SHA-256
digests of the **decoded** token bytes to configured project names. Use mode
0700 for the directory and 0600 for the file, readable by UID 1000. Rotate or
revoke tokens by atomically replacing the file within the mounted directory.
A revocation applies to subsequent requests.
- `home` owned by UID 1000 with an isolated Codex login in `auth.json`.
Keep this home dedicated to the worker. Supply the login only and keep user
configuration, MCP servers, skills, and other workload files out of it.
With that directory configured, the next normal Foundry deployment starts the
worker using the Linux binary built by ces-control and mounts the worker socket
and grants directory read-only. Normal backend deployments replace the worker with the same reviewed Linux build
and verify its private model catalog, restoring the previous worker if startup
fails. For manual maintenance, stop the managed worker before running
`bash deploy/codex-worker.sh /absolute/path/to/foundry`. The worker
runs the installed Codex CLI with fixed read-only, no-approval arguments and
disables command execution tools. It receives prompts via stdin and returns
the final agent message. The worker has no published port and Foundry receives
neither the Codex home nor the Docker socket. Keep both containers on the same
host for Unix socket access.
### Board Canvas snapshots and slugs
Apply `db/003-canvas.sql` through the normal migration runner before starting this
version. `GET /projects/{project}/workspaces/{workspace}/materials/{board}/canvas`
returns `{version, document}` and a quoted `ETag`. An untouched board returns
version 1 and an empty schema-1 graph. `PATCH` takes `{document: <full snapshot>}`
and the quoted `If-Match`; it atomically replaces the snapshot and returns
`{version}` with the new `ETag`. Canvas and material metadata have separate
versions. GET uses existing material read permissions; PATCH requires editor or
admin. Missing versions return 428, stale versions 412 `version_conflict`, invalid
graphs 400 `invalid_canvas`, and bodies over 5 MiB (UTF-8 bytes) 413. PNG/JPEG/WebP/
GIF data URLs up to 2 MiB decoded and HTTPS image URLs are supported. Temporary
node selection/drag/measurement state and mirrored styles are discarded.
Workspace and material create/get/list responses include `slug`. Create and
metadata PATCH accept an optional slug (1–100 lowercase ASCII letters/digits,
with single hyphens between segments; UUID-form custom values are reserved).
Workspace slugs are unique within a project, material slugs within a workspace;
duplicates return 409. Defaults use the ASCII name/title and UUID, falling back
to a generic prefix for names without ASCII letters/digits. Existing records are
backfilled. Renaming leaves slugs stable unless explicitly supplied. Workspace
and material path parameters accept either ID or slug, with unchanged permissions.
Canvas uses its board material's slug; there is no separate Canvas identity.
Slugs enable frontend SEO URLs but do not make private content public or add
search-engine metadata. Changing a custom slug does not retain an old alias.
Frontend follow-up: allowlist the Canvas proxy route and set its body limit to
at least 5 MiB; load the server snapshot, offer migration of old local drafts,
serialize autosaves and handle 412 explicitly. Restore node style dimensions
from width/height and render edges as Bézier curves. These frontend changes are
outside this Core delivery; local drafts alone are not database persistence.
Canvas schema 1 supports unframed images: `type: "plainImage"` with
`data.kind: "plain-image"`. They require the same validated `data.src` as image
cards, support geometry/rotation/frame membership, and cannot connect to edges.
This is a snapshot-format extension with no additional migration.
Canvas schema 1 also supports frames: `type: "frame"` with `data.kind: "frame"`.
Frame names use `data.title`; optional `data.labelMode` is `hidden`, `fixed`, or
`scaled` (frontend default: `fixed`). Frames cannot rotate, connect to edges,
or belong to other frames. Any non-frame node can specify `data.frameId`, which
must reference a frame in the same snapshot; forward references are supported.
Membership is explicit and independent of geometry: moving a frame over existing
content does not add members. The frontend assigns membership on content drop
and implements label zoom behavior. Core preserves the supplied membership and
label mode without inferring them from positions. Renderer-only `zIndex` is
ignored alongside transient state; restore frame layering in the frontend.
This extends existing JSONB snapshots and requires no additional migration.
### Browser session lifetime
Sessions use random, revocable bearer tokens rather than JWTs. New email and OAuth
logins have a 30-day idle lifetime; authenticated requests atomically renew that
idle deadline, capped at 90 days from issuance. Idle-expired, absolute-expired,
revoked and wrong-project tokens are never revived. Logout removes the session.
Apply `db/004-session-lifetime.sql` before running this version. Existing sessions
keep their prior idle expiry, so expired logins remain expired. For legacy rows,
the absolute 90-day cap starts at migration time because issuance was not recorded;
an unexpired legacy session gains the new idle lifetime on its next authenticated
request. New rows record their actual creation time and absolute deadline.
Login and exchange responses return `expires_in: 2592000`. Protected platform
responses and `/auth/me` include `X-Foundry-Session-Expires-In` with the remaining
seconds after renewal, shortened near the absolute deadline. The frontend proxy
must renew its HttpOnly cookie using that value, with a maximum of 30 days. It must
not extend a cookie beyond the backend-provided remaining lifetime, or expose the
session token to client JavaScript. CORS exposes the lifetime header alongside
ETag where applicable. The absolute deadline stays server-authoritative.
### Canvas V2 contract
Contract version: `canvas-v2-2026-11-06`. These routes are implemented on the
Canvas V2 work branch; they become available after that branch is reviewed,
merged and deployed. Do not infer production availability from this document.
`B` below means `/projects/{project}/workspaces/{workspace}/materials/{board}/canvas`.
Workspace and board path segments accept canonical UUIDs or existing slugs.
Responses and child relationships use canonical IDs. Authentication is the
existing **user session Bearer token**, with inherited material/workspace
permissions; the old project Codex service token is not accepted as a user login.
Reader/viewer accounts may read; mutations require editor/admin access.
The existing 30-day idle renewal and 90-day absolute session expiry are unchanged.
#### Snapshot compatibility and bounds
Use `Accept: application/vnd.foundry.canvas+json;version=2` for V2 clients.
GET remains `{version,document}`; PATCH accepts `{document}` and returns `{version}`.
The actual schema is in `document.schema_version` and `X-Canvas-Schema-Version`;
`ETag: "N"` is the independent canvas version. PATCH requires `If-Match: "N"`:
missing versions return 428, stale versions return 412 with zero writes.
V1 is still supported. Once a board is V2, legacy GET/PATCH and schema downgrades
return 409 `canvas_schema_upgrade_required`; no lossy V1 projection is returned.
GET does not create or migrate child boards.
Each canvas permits 500 nodes, 2,000 edges and 5 MiB of snapshot request data.
Coordinates and control vectors are finite, within ±1,000,000. Ordinary node
width/height are 20–3,000; V2 frame dimensions are 32–100,000. Ephemeral selection,
dragging, measured geometry and editor gesture state are not saved.
V2 edges preserve typed `data.appearance`, `animation`, `path` and `execution`:
| Field | Values / bounds |
| --- | --- |
| appearance | six-digit hex color; width 0.5–20; opacity 0.05–1; solid/dashed/dotted |
| head / tail | none/open-arrow/triangle/circle/diamond/square; size 4–32; boolean filled |
| animation | off/always/executing; flow/dash/pulse; forward/reverse; durationMs 250–30,000; hex color |
| path | bezier-chain; optional startControl/endControl; up to 64 ordered, uniquely identified knots |
| knot | position and relative in/out vectors; corner/smooth/symmetric; collinearity/length tolerance 1e-6 |
| execution.enabled | boolean; omitted means enabled; animation direction does not reverse dependencies |
Omitted appearance/animation fields remain omitted and use the original client
defaults (color `#AA968B`, width 1.5, solid, no markers, animation off).
No arbitrary CSS, SVG path strings, marker URLs or callbacks are accepted.
Text/script/image/plain-text/plain-image nodes can connect; icons cannot.
Frames connect through declared `port:<id>` handles, including nested port chains.
`GET B/capabilities` reports schema versions, actual worker availability and
limits. A configured catalog alone does not imply that every model can generate
images: image variants are enabled only for backend models explicitly verified
by the operator.
#### Subgraphs and cross-canvas transactions
Each linked frame owns one child board in the same project/workspace. The maximum
nesting depth is eight. The parent stores the frame and boundary edges; member
nodes and internal edges have exactly one owner, the child canvas. Child reads
and writes inherit the parent chain, including when addressed directly by ID.
Material lists omit child boards by default; `include_subgraphs=true` includes
accessible children with `parent_board_id` and `frame_id`.
Frame data retains `subgraph.boardId`, `ports`, and presentation:
`collapsed`, `contentScale` (0.05–4), `expandedSize`, `collapsedSize`.
Collapsing/scaling presentation does not rewrite child content. Projection is
`frame.position + (24,36) + contentScale * child.position`; viewport is independent.
| Route | Required input / behavior |
| --- | --- |
| POST B/connections | `{source,target,edge,expected_versions}` + Idempotency-Key; atomically creates/reuses boundary port chains and stores one edge in the lowest common ancestor |
| POST B/subgraphs | Parent If-Match; `{frame:{id,title,position,width,height,labelMode}}`; returns 201, child_board, parent/child snapshots and receipt |
| POST B/subgraphs/{frame}/members | `{source_board_id,target_board_id,node_ids,expected_versions}`; parent/child or siblings coordinated by their common parent |
| POST B/subgraphs/{frame}/dissolve | `{expected_versions}`; preserves content in the parent and archives the emptied child |
| POST B/subgraphs/migrate | `{dry_run:true}` creates no data; returns plan_id, digest, parent version and explicit members/edges/issues |
| POST B/subgraphs/migrate | `{dry_run:false,plan_id}` plus parent If-Match; stale plans return 412 |
| POST B/transactions/{id}/undo | `{expected_versions}`; restores snapshots and relationships atomically, increments current versions |
All mutating commands above require a UUID `Idempotency-Key` (case-insensitive).
Scope is project/workspace/user/resource/action. Canonical payload retries return
the same operation; a different payload returns 409 `idempotency_conflict`.
Records remain available for at least 24 hours. Read-only migration preflight
requires editor/admin but does not require an idempotency key or create a plan row.
`expected_versions` must include **every modified canvas**, including an ancestor
whose boundary port must change and child canvases whose ownership changes.
Missing versions return 428; any stale version returns 412 before commit.
All snapshots, versions, relationships, idempotency and receipt records share a
single SQL transaction. Boundary edges retain their IDs/styles/paths; ports are
stable and deduplicated. Node ID collisions and graph capacity errors reject the
entire command. Ordinary PATCH cannot detach linked frames, retarget ownership
or remove nodes still referenced across a boundary.
Undo receipts have an absolute `expires_at` and a seven-day lifetime; retries do
not extend it. Expired undo returns 409 `undo_receipt_expired`. Undo also checks
recorded after-state and current relationships, so incompatible edits return 412.
Undoing a later operation can restore a compatible state for an earlier undo
without resetting version counters. Redo uses the original command and a new key.
Migration considers only explicit legacy `frameId` membership, including empty
frames. It preserves internal and boundary edges, image references and styling,
converts coordinates/control points, and skips already linked frames. Original
snapshots and mapping data remain in the operation record for rollback.
#### Assets
`POST /projects/{project}/workspaces/{workspace}/assets` takes one multipart part
named `image` (or `file`) and an Idempotency-Key. PNG/JPEG/WebP/GIF are decoded,
not trusted by filename. The limit is 20 MiB and 40 million decoded pixels.
The response is `{id,mime_type,bytes,width,height,url}`. PostgreSQL stores the
encoded object, metadata and bindings atomically.
`GET .../assets/{id}` requires a user session and returns the actual image bytes
with the detected MIME and `nosniff`. Unbound objects are readable only by their
uploader or workspace admins; bound objects require access to an owning material
through its current parent chain. URLs are stable HTTPS application URLs, never
worker files or expiring signed URLs. Browser integrations should use an
authenticated fetch/proxy; do not persist temporary blob URLs in snapshots.
`data.assetId` is optional when `src` is already a stable managed URL. Moves,
dissolve and undo retain bindings; referenced images are not prematurely collected.
AI image inputs are frozen as authorized asset references. Existing inline images
and public HTTPS node images can be validated and frozen by Core. Fetches enforce
HTTPS, DNS/IP checks, bounded redirects/bytes/time, and reject private, loopback,
link-local and cloud metadata addresses. The worker receives validated bytes over
private Unix IPC, not arbitrary external download instructions.
#### AI models and runs
`GET B/ai/models` returns opaque IDs derived from the worker's real CLI catalog,
modalities, availability, input/timeout bounds and parameter schemas. Current CLI
variants expose an empty parameter object with `additionalProperties:false`;
raw CLI arguments and unknown parameters are rejected. No token, auth file, raw
CLI output or service configuration is included in browser responses.
Node `data.ai` stores enabled/modelId/prompt/propagate/parameters. Prompt length
is at most 16,000 characters; parameters encode to at most 16 KiB. Global AI panel
state, tool position and animation progress are client state, not snapshot data.
| Route | Input / result |
| --- | --- |
| POST B/ai/runs | If-Match + Idempotency-Key; `{node_id,model_id,prompt,parameters,propagate}`; returns 202 with run_id, poll_url, plan, canvas_version and ETag |
| GET B/ai/runs/{id} | after_seq >= 0, limit 1–100; status, plan, steps, events, next_seq, has_more, output metadata and applied_versions |
| GET B/ai/runs | status=active or a terminal status; include_descendants=true/false; limit 1–50; opaque next_cursor |
| POST B/ai/runs/{id}/cancel | Idempotency-Key; empty object/body; returns preserved applied steps and cancelled steps |
| POST B/ai/runs/{id}/apply | If-Match + Idempotency-Key; `{node_id,output_id}`; explicitly applies retained conflict output to its current target canvas |
Run admission atomically saves node configuration, increments the canvas version,
freezes the plan/fingerprints and records the task and key. A node has at most one
active step; another key targeting a busy node returns 409 `node_busy`. Queue
capacity is 128 active runs per project (429 `queue_full` with Retry-After).
Admission body is at most 256 KiB. Assembled model text is at most 1 MiB; inputs
allow four distinct images totaling 20 MiB. Text timeout is 90 seconds; verified
image variants use 180 seconds. The old `/codex/exec` limits remain unchanged.
Propagation is opt-in. It resolves nested ports to logical nodes, rejects cycles
and plans over 64 steps/depth 32 before invoking the worker, and stops at
unconfigured nodes. A topological schedule runs each node once; diamond joins
wait for every participating predecessor. Other referenced inputs are frozen
from their original snapshots. Incoming logical edge IDs order inputs stably.
Only connected canvases/port chains/static inputs are read, not every child board.
Runs persist across HTTP disconnects and Core restarts. Queue leases serialize
execution; expired uncertain executions fail with `execution_interrupted` rather
than being silently reissued. A worker's explicit pre-execution busy response is
safe to requeue, with completed predecessor results recovered from the database.
Worker output updates only current target text or src/assetId in a SQL transaction.
Node identity, dimensions, position, title and styling are retained. Content/AI
configuration changes produce conflict and retain the output; geometry-only edits
do not. Deletion, recreation, kind/ownership changes, revoked permission or cancel
prevent late writes. Image output must be an actual decoded managed image;
textual URLs are never accepted as completed image generation.
Events have monotonic per-run seq values and are replayable through polling.
Run states: queued/running/succeeded/partially_succeeded/failed/cancelled/conflict.
Step states additionally include skipped. Edge active/completed/failed/skipped
events drive execution-only animation; reverse visual animation does not reverse
execution. Cancellation commits terminal step states before acknowledging, retains
already applied results, and stops the worker through request cancellation at its
next heartbeat. It never implicitly rolls back applied output.
Text output is capped at 100,000 characters; failures keep original content.
Poll event pages are bounded to 100 events and approximately 800 KiB of event data.
Output metadata includes output IDs and image asset metadata; text content patches
are in replayable step.output/step.applied events. Runs/events are retained for at
least 30 days; referenced assets have no automatic destructive cleanup.
Errors use `{error,message?,details?,request_id?}`. Important statuses include
400 invalid_canvas/invalid_ai_request, 409 schema/idempotency/ownership/cycle
conflicts, 412 version_conflict, 428 version_required, 413 graph/context/asset
limits, 422 model_unavailable/model_incompatible and 429 queue_full. Asynchronous
generation failures are terminal step/run results, not successful empty content.
#### Remote verification and deployment
Normal `ces-control` CI runs formatting, tests, builds, migration checks and
isolated PostgreSQL integration tests. `deploy/check-canvas-real.sh bin/foundry`
is an explicit remote-runner-only real-model verification; it does not run in
normal CI. Set `FOUNDRY_CANVAS_IMAGE_MODELS` to backend names already verified for
image output. The check starts a temporary CLI worker and database and removes
both afterwards; the Core/test container never receives CLI login files.
On 2026-11-06, the isolated real check succeeded with text model
`codex-18061daa6ba6e3a576dda453d0df839f` and image variant
`codex-42cfda1d607e416417a1a0ac5c73d437`, backed by the installed CLI's
`gpt-6.1-sol`. The image decoded as PNG, 1254×1254, 857,723 bytes. These are
verification observations, not a hardcoded catalog or a production deployment
claim; temporary run/asset records were cleaned up. Always query the live catalog.
The isolated text run was `a38ea762-d3bf-41c2-a43a-679e5785f3d7`; the image run
was `6c0beaa0-d182-45b5-9075-110fcc800218` and its authenticated reread asset was
`bf2733bc-8aca-4bca-97dc-3cfa52d48270`, SHA-256
`2ffda6b1603fd0bab27f63479d7f2ad316b65f663afc57ba3f8fefa92a8edce4`.
These cleaned-up isolated IDs are audit observations, not live production resources.
For production, the worker can load operator-controlled `codex/canvas.env` with
`FOUNDRY_CANVAS_IMAGE_MODELS` containing verified backend names. Replace the worker
with the reviewed Linux build through the normal deployment process, apply the
numbered migrations and confirm capabilities before migrating a real canvas.
Production deployment of merge commit `b4e537b4adedeb524971cbbdd3f52c61257b10da`
succeeded on the confirmed ECS runner on 2026-11-06. Main checks
[run 912](https://gitea.entroia.com/Zayden-Jung/foundry-core/actions/runs/912)
and deployment
[run 913](https://gitea.entroia.com/Zayden-Jung/foundry-core/actions/runs/913)
both succeeded. The base URL is `https://api.foundry.entroia.com`.
The deployed capabilities endpoint reported contract `canvas-v2-2026-11-06`
with both text and image available; the worker uses the backend verified above.
Only the user-selected existing test canvas was migrated through the production
HTTPS API, using a temporary operator session with an absolute three-minute
expiry and the existing account's editor/admin permissions. Each preflight or
verification session was revoked immediately afterwards; no credential was
printed or persisted. The dry-run reported no issues, one legacy frame and two
explicit members. The version-bound migration committed atomically:
| Item | Verified value |
| --- | --- |
| Project | `endoleap` |
| Canonical workspace | `8d775c90-74c9-4109-a1ad-6d0ad3a00ac7` |
| Canonical parent board | `a9f9a985-e99a-43eb-b088-7edc9301452f` |
| Parent version/schema | 209 / V1 → 210 / V2 |
| Frame | `f2a00495-3740-43a6-aa52-611e4dd8520f` |
| Canonical child board | `9c9bd83b-2444-41f8-8e0e-bfd6d8873577` |
| Child version | 1 / V2 |
| Transaction | `4a6e6fee-683e-4025-8ef8-47092a80331b` |
| Undo expiry | `2026-11-13T10:56:40.241092Z` |
| Nodes | 11 preserved: parent 9, child 2 |
| Edges | 2 preserved in parent: 1 mapped boundary edge, 1 unchanged parent edge |
Authenticated V2 rereads matched the committed snapshots. The two explicit
members retained their content, image references, dimensions and styles, with
positions converted to child coordinates. The boundary edge retained its ID,
style and path, and references a stable port targeting the original node/handle.
Retrying the same operation returned the same transaction; a fresh dry-run
reported zero additional children. A legacy GET returned
409 `canvas_schema_upgrade_required`. No other canvas was migrated.
The source snapshot, plan, complete transaction response, reread snapshots and
summary are retained with mode 0600 under
`/opt/endoleap-infra/foundry/canvas-v2-migration-a9f9a985-e99a-43eb-b088-7edc9301452f`
on the ECS host, in addition to the database receipt. The frontend V2 integration
remains a separate task; use a V2-aware client for this migrated test canvas.
#### Creating new cross-boundary connections
Ordinary Canvas PATCH preserves existing frame ports and cannot add or retarget
ports. Migration/movement-generated ports are reusable, but creating a new
external connection to an unexposed child node requires this dedicated command:
`POST B/connections` with user session authorization,
`Accept: application/vnd.foundry.canvas+json;version=2`, JSON content type and a
UUID `Idempotency-Key`. Availability is advertised as
`capabilities.subgraphs.connections: true`; clients must check the deployed
capability before calling it.
`B` identifies the **lowest common ancestor board** of the two actual endpoints.
The coordinator may itself be a nested board. Both endpoints must be in this
same project/workspace and inside its active subgraph tree. A direct endpoint on
B is valid, as are siblings and descendants up to the existing depth limit.
When both endpoints are in the same board, use that board as B.
```json
{
"source": {"board_id":"<child-board-uuid>","node_id":"child-text","handle":"right"},
"target": {"board_id":"<parent-board-uuid>","node_id":"parent-image","handle":"left"},
"edge": {
"id":"new-edge",
"data": {
"appearance":{"color":"#AA968B","width":2},
"animation":{"mode":"executing","effect":"flow","direction":"forward","durationMs":1600},
"execution":{"enabled":true}
}
},
"expected_versions": {"<parent-board-uuid>":210,"<child-board-uuid>":1}
}
```
Use canonical board UUIDs for endpoints and version keys. Eligible real node
kinds are text/script/plain-text/image/plain-image; handles must be one of
`top/right/bottom/left`. Do not submit projected node IDs, frame IDs as generated
content, or `port:*` handles. The server exposes a real endpoint through each
containing frame, creating or reusing a port with the matching
`direction/nodeId/handle` tuple. Existing matching ports retain their IDs,
including migration-created or custom stable IDs. A source chain uses output
ports, and a target chain uses input ports; these are distinct. No unbound port
or writable arbitrary child reference is accepted.
The expected_versions map must contain **exactly every board on both paths**,
including the endpoint boards and B. For a grandchild-to-parent connection it
contains parent, intermediate child and grandchild; for siblings it contains
both children and their parent. No separate If-Match header is required for this
multi-board operation. Missing participants return 428 `version_required`;
when a nonempty map has missing/extra participant keys, the response includes
`details.required_board_ids`. Any stale version returns 412 `version_conflict`.
All participants require current editor/admin access. Calling a higher ancestor
instead of the lowest common ancestor returns 409 `connection_owner_mismatch`.
An unrelated/invalid ownership path returns 409 `ownership_conflict`; resources
outside the caller's scope retain the normal 403/404 behavior.
Only `edge.id` and optional typed V2 `edge.data` are accepted. Its appearance,
animation, execution flag and bezier-chain path follow the normal V2 validation.
All knots are already in B's local coordinates; port creation does not move node
geometry or re-layout the edge. An existing edge ID in B returns 409
`edge_id_conflict`. Graph, port and snapshot capacity failures return 413 without
saving any ports, edges, versions or receipt.
Success is 201 with the coordinator's ETag and:
```json
{
"transaction_id":"<uuid>",
"parent":{"board_id":"<coordinator>","version":211,"document":{}},
"snapshots":[
{"board_id":"<coordinator>","version":211,"document":{}},
{"board_id":"<child-board-uuid>","version":2,"document":{}}
],
"connection":{
"board_id":"<coordinator>",
"edge":{"id":"new-edge","source":"<frame-id>","sourceHandle":"port:<stable-id>","target":"parent-image","targetHandle":"left","data":{}},
"source":{"board_id":"<child-board-uuid>","node_id":"child-text","handle":"right"},
"target":{"board_id":"<parent-board-uuid>","node_id":"parent-image","handle":"left"}
},
"created_ports":[{"board_id":"<coordinator>","frame_id":"<frame-id>","port_id":"<stable-id>"}],
"undo_receipt":{"transaction_id":"<uuid>","valid_for_seconds":604800,"expires_at":"<RFC3339 timestamp>"}
}
```
The JSON above abbreviates document values and shows a one-level example; nested
connections include every intermediate board in snapshots. The response edge is
the stored owner-board edge, while source/target preserve the logical endpoint
identities. created_ports contains only newly allocated ports; reused ports are
available in the snapshots. Each participating board advances exactly one
version (including endpoint boards whose node content remains unchanged),
consistent with other cross-board commands. Flush pending saves before creating
the connection, then absorb **all** returned versions/snapshots before resuming
autosave. Retrying an identical body with the same key returns the original 201
response and does not advance versions again. Changing the body, including its
version map, with that key returns 409 `idempotency_conflict`.
Undo uses the existing `POST B/transactions/{transaction_id}/undo` endpoint with
a new key and all current participant versions. It restores the previous edge
and port arrays atomically; subsequent incompatible edits cause 412. Existing
ports reused by the command remain after undo. Redo submits the command with
fresh versions and a new key. Ordinary PATCH can continue to edit/remove edges
using already exposed ports, but cannot retarget or directly delete the ports.
#### Reproducible session API examples
These examples require Bash, curl and jq, an editor/admin login session, and an
explicitly selected board. Set `SESSION_TOKEN` in memory; use the user session,
never the legacy Codex service token. Run mutations only on a board intended for
V2 testing. Each successful mutation changes versions: reread before the next
operation. Reuse the same key and identical body when retrying an operation.
```bash
API=https://api.foundry.entroia.com
PROJECT=your-project
WORKSPACE=your-workspace-id-or-slug
BOARD=your-board-id-or-slug
B="$API/projects/$PROJECT/workspaces/$WORKSPACE/materials/$BOARD/canvas"
api() {
curl --fail-with-body --silent --show-error \
-H "Authorization: Bearer $SESSION_TOKEN" \
-H 'Accept: application/vnd.foundry.canvas+json;version=2' "$@"
}
# V2-aware read; capabilities report actual deployment and model availability.
api "$B/capabilities"
snapshot=$(api "$B")
version=$(jq -r '.version' <<<"$snapshot")
# Save an unchanged document, explicitly upgrading the envelope to V2.
payload=$(jq '{document:(.document | .schema_version=2)}' <<<"$snapshot")
api -X PATCH "$B" -H 'Content-Type: application/json' \
-H "If-Match: \"$version\"" --data-binary "$payload"
# Create an empty real child with its parent frame, atomically.
version=$(api "$B" | jq -r '.version')
create_key=$(uuidgen)
api -X POST "$B/subgraphs" -H 'Content-Type: application/json' \
-H "If-Match: \"$version\"" -H "Idempotency-Key: $create_key" \
--data '{"frame":{"id":"example-frame","title":"Example","position":{"x":100,"y":100},"width":640,"height":400,"labelMode":"fixed"}}'
# Read-only old-frame preflight. Inspect issues/counts/mappings before executing.
plan=$(api -X POST "$B/subgraphs/migrate" -H 'Content-Type: application/json' \
--data '{"dry_run":true}')
printf '%s\n' "$plan" | jq .
```
After reviewing that preflight, execute precisely its returned plan with a new
UUID key and the unchanged parent version. Any intervening change returns 412;
repeat preflight instead of forcing a stale migration.
```bash
version=$(api "$B" | jq -r '.version')
migrate_key=$(uuidgen)
payload=$(jq '{dry_run:false,plan_id:.plan_id}' <<<"$plan")
api -X POST "$B/subgraphs/migrate" -H 'Content-Type: application/json' \
-H "If-Match: \"$version\"" -H "Idempotency-Key: $migrate_key" \
--data-binary "$payload"
models=$(api "$B/ai/models")
printf '%s\n' "$models" | jq .
TEXT_MODEL=$(jq -r '[.models[] | select(.available and (.output_modalities | index("text")))][0].id // empty' <<<"$models")
IMAGE_MODEL=$(jq -r '[.models[] | select(.available and (.output_modalities | index("image")))][0].id // empty' <<<"$models")
# Supply existing eligible node IDs from the selected board.
TEXT_NODE=your-text-node
IMAGE_NODE=your-image-node
run_node() {
local node="$1" model="$2" propagate="$3" prompt="$4" version key payload
test -n "$model" || { printf 'No available model for this modality\n' >&2; return 1; }
version=$(api "$B" | jq -r '.version')
key=$(uuidgen)
payload=$(jq -n --arg node "$node" --arg model "$model" --arg prompt "$prompt" \
--argjson propagate "$propagate" \
'{node_id:$node,model_id:$model,prompt:$prompt,parameters:{},propagate:$propagate}')
api -X POST "$B/ai/runs" -H 'Content-Type: application/json' \
-H "If-Match: \"$version\"" -H "Idempotency-Key: $key" --data-binary "$payload"
}
text_run=$(run_node "$TEXT_NODE" "$TEXT_MODEL" false 'Summarize this content')
run_id=$(jq -r '.run_id' <<<"$text_run")
api "$B/ai/runs/$run_id?after_seq=0&limit=100"
api "$B/ai/runs?status=active&include_descendants=true&limit=50"
```
Wait for a terminal status before starting another run on the same node. Continue
polling from `next_seq` while `has_more` is true, then retain the cursor for the
next poll. Image generation and propagation use the same asynchronous contract:
```bash
image_run=$(run_node "$IMAGE_NODE" "$IMAGE_MODEL" false 'Generate an image from this reference')
image_run_id=$(jq -r '.run_id' <<<"$image_run")
api "$B/ai/runs/$image_run_id?after_seq=0&limit=100"
# Once succeeded, outputs[].output.src is an authenticated managed image URL.
# Fetch that URL with api and --output to verify the actual image bytes.
# Configure downstream node data.ai and execution edges before propagation.
propagated_run=$(run_node "$TEXT_NODE" "$TEXT_MODEL" true 'Transform and propagate')
api "$B/ai/runs/$(jq -r '.run_id' <<<"$propagated_run")?after_seq=0&limit=100"
```
The live catalog, rather than the isolated verification IDs above, determines
whether each request can run. A 202 response acknowledges a queued job; use its
terminal status and authenticated canvas/asset rereads as completion evidence.
### Managed image previews
Original asset bytes remain immutable and are used by the ordinary asset URL,
downloads and AI inputs. Authenticated `GET .../assets/{id}?variant=preview`
returns one display rendition bounded to 1024 pixels on its longest edge. Opaque previews use JPEG quality 82, transparency stays PNG, GIF preserves
the original animation, and JPEG EXIF orientation is applied. Small originals
may be returned unchanged when this is more efficient. No preview URL belongs
in node `data.src`: persist the original managed URL and optional original
`assetId`, then select the display variant only in the renderer.
Permissions are checked on every read, including cache hits. Originals are not
replaced. Generation is serialized and the immutable encoded preview cache is
bounded to 32 MiB / 128 entries. Current capabilities advertise `assets.previews`
and `assets.preview_max_edge`. No database migration is needed. Asset reads and
Canvas GET release their permission transaction before encoding/writing the
response. Uploads release the initial workspace lock before receiving a large
multipart body and recheck current write permission before committing.
Legacy inline images must be migrated through an explicit editor action: upload
unchanged bytes with idempotency keys, then save the same node IDs/geometry with
managed asset references and the current canvas version. Opening a canvas does
not migrate it or cause an implicit PATCH.
#### Atomic member drop positions
`POST B/subgraphs/{frame}/members` additionally accepts optional `positions`, an object with exactly one `{x,y}` entry for each `node_ids` item, expressed in the **source board's local coordinates**. Both coordinates are required, finite and within ±1,000,000. Capabilities advertise `subgraphs.member_positions: true`. Omission preserves legacy behavior. Positions, ownership, edge/port conversion, versions and undo receipt commit in one transaction; no preceding coordinate PATCH is needed. Validation failures or stale versions perform zero writes. The positions participate in the idempotency payload digest; retries must keep the entire body and key unchanged. Undo restores the pre-drop snapshot, including original positions.
## 源码阅读注释
Go 实现、测试与部署脚本内的中文注释说明调用关系、事务、版本、身份和资源生命周期。历史 `db/*.sql` 由部署校验和锁定,逐迁移、逐表及约束说明集中在 [数据库注释索引](docs/database-comments.sql),保留历史 SQL 字节以兼容已部署数据库。`go.sum` 和协议 JSON fixture 保留机器可读原文,不插入注释。
+30
View File
@@ -0,0 +1,30 @@
# Manual SQL verification
`ci/check-sql.sh` runs storage checks against SQLite and temporary PostgreSQL and MySQL containers. Run it from the workspace root on an approved remote runner. It removes its test containers and network on exit.
## Automatic deployment
```mermaid
flowchart TD
M["main 收到提交"] --> W["deploy.yml 在 ces-control 上启动"]
W --> B["build-release.sh 编译 backend 发布版"]
B -->|Bedrock 二进制和 Git SHA| R
E["Gitea PostgreSQL Variables 和 Secret"] -->|部署参数| P
subgraph release["release.sh"]
R["暂存待发布版本"] --> P["调用 render-postgres.py 生成私有 bedrock.yaml"]
P -->|配置就绪| I["临时容器运行 backend 的 --init-storage,初始化 PostgreSQL"]
I -->|成功| S["保存版本并原子切换 current"]
P -->|失败| F["清理暂存目录,保留现有 current"]
I -->|失败| F
end
```
## Manual SQL checks
```mermaid
flowchart TD
H["在远程 runner 手动运行"] --> C["ci/check-sql.sh 创建临时网络和数据库容器"]
C --> T["测试 SQLite、PostgreSQL 和 MySQL"]
T -->|退出时| U["清理测试容器和临时网络"]
```
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env bash
set -euo pipefail
prefix="bedrock-sql-$(openssl rand -hex 8)"
password="$(openssl rand -hex 16)"
cleanup() {
docker rm -f "$prefix-rust" "$prefix-mysql" "$prefix-postgres" >/dev/null 2>&1 || true
docker network rm "$prefix" >/dev/null 2>&1 || true
}
trap cleanup EXIT
docker network create "$prefix" >/dev/null
docker run -d --name "$prefix-postgres" --network "$prefix" --network-alias postgres \
-e POSTGRES_PASSWORD="$password" -e POSTGRES_DB=bedrock postgres:17-alpine >/dev/null
docker run -d --name "$prefix-mysql" --network "$prefix" --network-alias mysql \
-e MYSQL_RANDOM_ROOT_PASSWORD=1 -e MYSQL_USER=bedrock -e MYSQL_PASSWORD="$password" \
-e MYSQL_DATABASE=bedrock mysql:8.4 >/dev/null
wait_for() {
for _ in {1..90}; do
if "$@" >/dev/null 2>&1; then return; fi
sleep 2
done
"$@"
}
wait_for docker exec "$prefix-postgres" pg_isready -h 127.0.0.1 -U postgres -d bedrock
docker exec -e PGPASSWORD="$password" "$prefix-postgres" \
createdb -h 127.0.0.1 -U postgres bedrock_replica
wait_for docker exec -e MYSQL_PWD="$password" "$prefix-mysql" \
mysql -h 127.0.0.1 -u bedrock -D bedrock -e 'SELECT 1'
docker run --rm --name "$prefix-rust" --network "$prefix" \
--mount "type=bind,src=$PWD,dst=/work,readonly" -w /work \
-e CARGO_TARGET_DIR=/tmp/bedrock-target \
-e BEDROCK_REQUIRE_SQL_TESTS=1 \
-e BEDROCK_TEST_POSTGRES="postgres://postgres:$password@postgres/bedrock" \
-e BEDROCK_TEST_POSTGRES_REPLICA="postgres://postgres:$password@postgres/bedrock_replica" \
-e BEDROCK_TEST_MYSQL="mysql://bedrock:$password@mysql/bedrock" \
rust:1.91.1-bookworm sh -ec '
rustup component add rustfmt
cargo fmt --all --check
cargo test --locked --workspace
cargo build --locked --workspace
cd "$(mktemp -d)"
BEDROCK_BACKEND_LISTEN=invalid /tmp/bedrock-target/debug/backend --init-storage
test -f bedrock.sqlite3
'
-116
View File
@@ -1,116 +0,0 @@
// Foundry 进程装配入口:HTTP 服务连接认证、平台、研究库和 Codex Unix socket。
package main
import (
"context"
"encoding/json"
"log"
"net"
"net/http"
"net/url"
"os"
"time"
"gitea.entroia.com/Zayden-Jung/foundry-core/internal/auth"
"gitea.entroia.com/Zayden-Jung/foundry-core/internal/codex"
"gitea.entroia.com/Zayden-Jung/foundry-core/internal/platform"
"gitea.entroia.com/Zayden-Jung/foundry-core/internal/research"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/stdlib"
)
// env 将空环境变量视为缺省;仅用于允许默认值的配置项。
func env(key, fallback string) string {
if value := os.Getenv(key); value != "" {
return value
}
return fallback
}
// main 支持独立 codex-worker 模式,其余启动方式进入 HTTP API 服务。
func main() {
if len(os.Args) == 2 && os.Args[1] == "codex-worker" {
log.Fatal(codex.ServeWorker("/run/foundry-codex/worker.sock"))
}
// 公共 origin 只允许 HTTPS 根地址,回调路径由程序拼接,避免配置夹带查询或用户信息。
origin, err := url.Parse(os.Getenv("PUBLIC_ORIGIN"))
if err != nil || origin.Scheme != "https" || origin.Hostname() == "" || origin.User != nil ||
(origin.Path != "" && origin.Path != "/") || origin.RawQuery != "" || origin.Fragment != "" {
log.Fatal("PUBLIC_ORIGIN must be an HTTPS origin")
}
var callbacks map[string]string
if err := json.Unmarshal([]byte(os.Getenv("FOUNDRY_PROJECTS")), &callbacks); err != nil || len(callbacks) == 0 {
log.Fatal("FOUNDRY_PROJECTS must configure at least one project")
}
id, secret, dsn := os.Getenv("GOOGLE_CLIENT_ID"), os.Getenv("GOOGLE_CLIENT_SECRET"), os.Getenv("DATABASE_URL")
if id == "" || secret == "" || dsn == "" {
log.Fatal("Google credentials and DATABASE_URL are required")
}
config, err := pgx.ParseConfig(dsn)
if err != nil {
log.Fatal("Invalid DATABASE_URL")
}
// OpenDB 创建连接池,实际连接按需建立;HTTP 就绪检查再验证主库可用性。
db := stdlib.OpenDB(*config)
defer db.Close()
email, err := auth.EmailConfigFromEnv()
if err != nil {
log.Fatal(err)
}
// nil 邮件配置会直接返回;此后台任务使用进程级上下文,没有单独的优雅停机取消。
go email.Run(context.Background(), db)
slack, err := auth.SlackConfigFromEnv(origin.ResolveReference(&url.URL{Path: "/auth/slack/callback"}).String())
if err != nil {
log.Fatal(err)
}
handler, err := auth.New(db, callbacks, origin.ResolveReference(&url.URL{Path: "/auth/google/callback"}).String(), id, secret, email, slack)
if err != nil {
log.Fatal(err)
}
mux := http.NewServeMux()
// 研究数据使用可选、独立且只读的连接池;配置后必须在五秒启动探测内可访问。
var papers research.Repository
if researchDSN := os.Getenv("FOUNDRY_RESEARCH_DATABASE_URL"); researchDSN != "" {
researchConfig, err := pgx.ParseConfig(researchDSN)
if err != nil {
log.Fatal("Invalid research database configuration")
}
researchConfig.RuntimeParams["default_transaction_read_only"] = "on"
researchConfig.RuntimeParams["application_name"] = "foundry-research"
researchDB := stdlib.OpenDB(*researchConfig)
defer researchDB.Close()
researchDB.SetMaxOpenConns(2)
researchDB.SetMaxIdleConns(2)
researchDB.SetConnMaxIdleTime(5 * time.Minute)
researchDB.SetConnMaxLifetime(30 * time.Minute)
repository, err := research.NewPostgresRepository(researchDB, env("FOUNDRY_RESEARCH_SCHEMA", "research"))
if err != nil {
log.Fatal("Invalid research database configuration")
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
err = repository.Check(ctx)
cancel()
if err != nil {
log.Fatal("Research database is unavailable or not published")
}
papers = repository
}
// 先注册具体业务路径,最后的根处理器承接认证及健康探测请求。
research.Register(mux, papers, callbacks)
if err := codex.Register(mux, callbacks, os.Getenv("FOUNDRY_CODEX_SOCKET"), os.Getenv("FOUNDRY_CODEX_GRANTS")); err != nil {
log.Fatal(err)
}
onboarding, err := platform.ParseOnboarding(os.Getenv("FOUNDRY_ONBOARDING"), callbacks)
if err != nil {
log.Fatal(err)
}
platform.Register(mux, db, callbacks, origin.Scheme+"://"+origin.Host, onboarding, codex.NewCanvasClient(os.Getenv("FOUNDRY_CODEX_SOCKET")))
mux.Handle("/", handler)
// HOST 默认只监听回环,容器部署显式覆盖;较长写超时用于耗时业务响应。
server := &http.Server{
Addr: net.JoinHostPort(env("HOST", "127.0.0.1"), env("PORT", "8080")),
Handler: mux, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second,
WriteTimeout: 110 * time.Second, IdleTimeout: 60 * time.Second,
}
log.Fatal(server.ListenAndServe())
}
+11
View File
@@ -0,0 +1,11 @@
[package]
name = "admin_backend"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
[dependencies]
axum.workspace = true
clusters.workspace = true
serde.workspace = true
subtle.workspace = true
+120
View File
@@ -0,0 +1,120 @@
use std::{io, sync::Arc};
use axum::{
Json, Router,
extract::{Request, State},
http::{HeaderMap, StatusCode, header},
middleware::{self, Next},
response::{IntoResponse, Response},
routing::get,
};
use clusters::{DOCUMENTS, ResolvedDeployment, SqlDriver};
use serde::Serialize;
use subtle::ConstantTimeEq;
#[derive(Clone)]
struct AdminState {
config: Arc<ResolvedDeployment>,
config_version: Option<String>,
storage_driver: &'static str,
read_only: bool,
}
#[derive(Serialize)]
struct DeploymentStatus<'a> {
deployment: &'a str,
config_version: Option<&'a str>,
storage_driver: &'static str,
read_only: bool,
}
impl AdminState {
fn status(&self) -> DeploymentStatus<'_> {
let config = &self.config;
DeploymentStatus {
deployment: &config.deployment,
config_version: self
.config_version
.as_deref()
.or(Some(&config.config_version)),
storage_driver: self.storage_driver,
read_only: self.read_only,
}
}
}
pub fn router(
config: Arc<ResolvedDeployment>,
config_version: Option<String>,
token: String,
) -> io::Result<Router> {
if token.is_empty() || !token.bytes().all(|byte| byte.is_ascii_graphic()) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"BEDROCK_ADMIN_TOKEN must contain visible ASCII characters without spaces",
));
}
let settings = config
.binding(DOCUMENTS)
.and_then(|resource| resource.as_sql())
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
"documents must reference a SQL resource",
)
})?;
let storage_driver = match settings.driver {
SqlDriver::Sqlite => "sqlite",
SqlDriver::Postgres => "postgres",
SqlDriver::Mysql => "mysql",
};
let read_only = settings.read_only;
let admin = Router::new()
.route("/status", get(deployment_status))
.route_layer(middleware::from_fn_with_state(
Arc::<str>::from(token),
require_admin,
));
Ok(Router::new()
.route("/healthz", get(|| async { StatusCode::NO_CONTENT }))
.route("/readyz", get(|| async { StatusCode::NO_CONTENT }))
.nest("/admin/v1", admin)
.with_state(AdminState {
config,
config_version,
storage_driver,
read_only,
}))
}
async fn deployment_status(State(state): State<AdminState>) -> Response {
([(header::CACHE_CONTROL, "no-store")], Json(state.status())).into_response()
}
async fn require_admin(State(token): State<Arc<str>>, request: Request, next: Next) -> Response {
if authorized(request.headers(), &token) {
next.run(request).await
} else {
(
StatusCode::UNAUTHORIZED,
[(header::WWW_AUTHENTICATE, "Bearer")],
)
.into_response()
}
}
fn authorized(headers: &HeaderMap, token: &str) -> bool {
let mut values = headers.get_all(header::AUTHORIZATION).iter();
let Some(value) = values.next().and_then(|value| value.to_str().ok()) else {
return false;
};
if values.next().is_some() {
return false;
}
let Some((scheme, supplied)) = value.split_once(' ') else {
return false;
};
scheme.eq_ignore_ascii_case("Bearer") && bool::from(supplied.as_bytes().ct_eq(token.as_bytes()))
}
+12
View File
@@ -0,0 +1,12 @@
[package]
name = "backend"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
[dependencies]
admin_backend = { path = "../admin_backend" }
axum.workspace = true
clusters.workspace = true
database.workspace = true
tokio = { workspace = true, features = ["net", "signal", "sync", "time"] }
+17
View File
@@ -0,0 +1,17 @@
use std::{sync::Arc, time::Duration};
use axum::{Router, extract::State, http::StatusCode, routing::get};
pub fn router(db: database::Connection) -> Router {
Router::new()
.route("/healthz", get(|| async { StatusCode::NO_CONTENT }))
.route("/readyz", get(readiness))
.with_state(Arc::new(db))
}
async fn readiness(State(db): State<Arc<database::Connection>>) -> StatusCode {
match tokio::time::timeout(Duration::from_secs(2), db.revision()).await {
Ok(Ok(_)) => StatusCode::NO_CONTENT,
_ => StatusCode::SERVICE_UNAVAILABLE,
}
}
+140
View File
@@ -0,0 +1,140 @@
use std::{env, error::Error, io, net::SocketAddr, sync::Arc};
use axum::Router;
use clusters::{DOCUMENTS, DeploymentConfig, ResolvedDeployment};
use database::{ConnectError, connect_resolved, connect_sql};
use tokio::{net::TcpListener, sync::watch};
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let mut args = env::args_os().skip(1);
let init_storage = match (args.next(), args.next()) {
(None, None) => false,
(Some(arg), None) if arg == "--init-storage" => true,
_ => {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"expected no arguments or --init-storage",
)
.into());
}
};
let config = match env::var_os("BEDROCK_DB_CONFIG") {
Some(path) => DeploymentConfig::load(path)?,
None => DeploymentConfig::default(),
}
.resolve()?;
if init_storage {
return initialize_storage(&config).await;
}
let address: SocketAddr = optional_env("BEDROCK_BACKEND_LISTEN")?
.as_deref()
.unwrap_or("127.0.0.1:8080")
.parse()?;
let config = Arc::new(config);
let admin_address = optional_env("BEDROCK_ADMIN_LISTEN")?;
let admin = match optional_env("BEDROCK_ADMIN_TOKEN")? {
Some(token) => {
let address: SocketAddr = admin_address
.as_deref()
.unwrap_or("127.0.0.1:8081")
.parse()?;
let router = admin_backend::router(
Arc::clone(&config),
optional_env("BEDROCK_CONFIG_VERSION")?,
token,
)?;
Some((TcpListener::bind(address).await?, router))
}
None if admin_address.is_some() => {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"BEDROCK_ADMIN_LISTEN requires BEDROCK_ADMIN_TOKEN",
)
.into());
}
None => None,
};
let listener = TcpListener::bind(address).await?;
let db = connect_resolved(&config).await?;
println!("Bedrock backend listening on {}", listener.local_addr()?);
let (stop, shutdown_signal) = watch::channel(false);
tokio::spawn(async move {
shutdown().await;
stop.send_replace(true);
});
if let Some((admin_listener, admin_router)) = admin {
println!("Bedrock admin listener on {}", admin_listener.local_addr()?);
tokio::try_join!(
serve(listener, backend::router(db), shutdown_signal.clone()),
serve(admin_listener, admin_router, shutdown_signal),
)?;
} else {
serve(listener, backend::router(db), shutdown_signal).await?;
}
Ok(())
}
async fn initialize_storage(resolved: &ResolvedDeployment) -> Result<(), Box<dyn Error>> {
if resolved
.binding(DOCUMENTS)
.is_some_and(|resource| resource.as_sql().is_none())
{
return Err(ConnectError::InvalidDocuments.into());
}
for (role, resource) in resolved.bound_resources() {
let Some(settings) = resource.as_sql() else {
continue;
};
let connection = connect_sql(settings).await?;
println!(
"Bedrock storage ready (config {}, role {}, {:?}, revision {}, read-only: {})",
resolved.config_version,
role,
connection.driver(),
connection.revision().await?,
connection.is_read_only(),
);
}
Ok(())
}
fn optional_env(name: &str) -> Result<Option<String>, env::VarError> {
match env::var(name) {
Ok(value) => Ok(Some(value)),
Err(env::VarError::NotPresent) => Ok(None),
Err(error) => Err(error),
}
}
async fn serve(
listener: TcpListener,
router: Router,
mut shutdown_signal: watch::Receiver<bool>,
) -> io::Result<()> {
axum::serve(listener, router)
.with_graceful_shutdown(async move {
let _ = shutdown_signal.wait_for(|stop| *stop).await;
})
.await
}
async fn shutdown() {
#[cfg(unix)]
{
use tokio::signal::unix::{SignalKind, signal};
if let Ok(mut terminate) = signal(SignalKind::terminate()) {
tokio::select! {
_ = terminate.recv() => {},
_ = tokio::signal::ctrl_c() => {},
}
return;
}
}
let _ = tokio::signal::ctrl_c().await;
}
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "clusters"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
[dependencies]
serde.workspace = true
serde_json.workspace = true
serde-saphyr.workspace = true
toml.workspace = true
thiserror.workspace = true
url.workspace = true
+38
View File
@@ -0,0 +1,38 @@
# clusters
`clusters` 负责读取和校验 Bedrock 的部署配置,并解析出各用途的连接参数。
`resources` 存放按名称索引的资源,`bindings` 把用途绑定到资源名。目录增删改查使用同一套接口。资源枚举将具体校验和解析交给对应的后端模块。
`transport.rs` 提供共享的 `Address` 和 `Tls`。SQL 通过 `tls` 字段配置 TLS,S3 从 endpoint 的协议得到 TLS 策略。省略 S3 endpoint 时使用默认 HTTPS 地址。
## 模块依赖
箭头从使用方指向定义类型或提供功能的模块。图中省略 `mod` 声明和 `pub use` 导出。旧配置结构在 `format.rs` 转成统一目录。
```mermaid
flowchart LR
lib["lib.rs"] -->|解析资源和用途| res["resource.rs"]
lib --> err["error.rs"]
cat["catalog.rs"] -->|为 DeploymentConfig 实现 CRUD| lib
cat -->|统一校验资源| res
cat --> err
res -->|SQL 配置和解析| sql["sql.rs"]
res -->|对象存储配置和解析| obj["object_storage.rs"]
res -->|统一驱动类型| drv["driver.rs"]
res --> err
sql -->|SqlDriver| drv
obj -->|ObjectStoreDriver| drv
sql -->|Address 和 Tls| net["transport.rs"]
obj -->|Address 和 Tls| net
sql --> err
obj --> err
fmt["format.rs"] -->|读取和输出 DeploymentConfig| lib
fmt -->|导入时调用 insert_resource| cat
fmt -->|读取资源格式| res
fmt -->|读取旧 SQL 配置| sql
fmt -->|读取旧对象存储配置| obj
fmt --> err
```
+48
View File
@@ -0,0 +1,48 @@
//! Named resource lookup and editing.
use std::mem::discriminant;
use crate::{ConfigError, DeploymentConfig, Resource, ResourceRef, validate_name};
impl DeploymentConfig {
pub fn resource(&self, name: &str) -> Option<ResourceRef<'_>> {
self.resources.get(name)
}
pub fn resources(&self) -> impl Iterator<Item = (&str, ResourceRef<'_>)> {
self.resources
.iter()
.map(|(name, resource)| (name.as_str(), resource))
}
pub fn insert_resource(&mut self, name: String, resource: Resource) -> Result<(), ConfigError> {
if self.resources.contains_key(&name) {
return Err(ConfigError::DuplicateResource);
}
self.store_resource(name, resource)
}
pub fn update_resource(&mut self, name: &str, resource: Resource) -> Result<(), ConfigError> {
let previous = self.resource(name).ok_or(ConfigError::MissingResource)?;
if discriminant(previous) != discriminant(&resource) {
return Err(ConfigError::ResourceCategory);
}
self.store_resource(name.to_owned(), resource)
}
pub fn remove_resource(&mut self, name: &str) -> Result<Resource, ConfigError> {
if self.bindings.values().any(|target| target == name) {
return Err(ConfigError::ResourceInUse);
}
self.resources
.remove(name)
.ok_or(ConfigError::MissingResource)
}
fn store_resource(&mut self, name: String, resource: Resource) -> Result<(), ConfigError> {
validate_name(&name, "resource")?;
resource.resolve(&self.deployment, Some(&name), self.read_only)?;
self.resources.insert(name, resource);
Ok(())
}
}
+64
View File
@@ -0,0 +1,64 @@
//! Driver definitions shared by the backend configuration modules.
use serde::{Deserialize, Serialize};
/// Common backend type for catalog lookups in Rust.
///
/// Serialized configuration uses category-specific driver types in its fields.
/// Deriving Serde traits on this enum would also require them on every wrapped type.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Driver {
Sql(SqlDriver),
ObjectStore(ObjectStoreDriver),
// Reserved categories gain Serde traits when their configuration fields are added.
Cache(CacheDriver),
Search(SearchDriver),
EventStream(EventStreamDriver),
BatchCompute(BatchComputeDriver),
OnlineService(OnlineServiceKind),
}
/// The driver in SQL cluster configuration. Serde uses snake_case names such as `postgres`.
/// `SqlDriver::default()` selects `Sqlite`.
#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum SqlDriver {
#[default]
Sqlite,
Postgres,
Mysql,
}
/// The driver in object storage configuration. Serde reads and writes `S3` as `s3`.
#[derive(Clone, Copy, Debug, Deserialize, Serialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ObjectStoreDriver {
S3,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CacheDriver {
Redis,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SearchDriver {
OpenSearch,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum EventStreamDriver {
Kafka,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BatchComputeDriver {
Spark,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum OnlineServiceKind {
Recommendation,
Retrieval,
Ranking,
}
+35
View File
@@ -0,0 +1,35 @@
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ConfigError {
#[error("invalid {0} name")]
Name(&'static str),
#[error("the selected database cluster is not configured")]
UnknownCluster,
#[error("a cluster must be selected when clusters are configured")]
ClusterRequired,
#[error("legacy cluster and sql.documents refer to different resources")]
ConflictingDocuments,
#[error("binding {role} references unknown resource {target}")]
UnknownBinding { role: String, target: String },
#[error("conflicting bindings for role {0}")]
ConflictingBinding(String),
#[error("invalid object storage configuration")]
ObjectStorage,
#[error("resource already exists")]
DuplicateResource,
#[error("resource does not exist")]
MissingResource,
#[error("resource is referenced by a deployment binding")]
ResourceInUse,
#[error("a resource update must preserve its category")]
ResourceCategory,
#[error("the database pool size must be greater than zero")]
PoolSize,
#[error("SQLite does not support a replica list")]
SqliteReplicas,
#[error("invalid SQLite file path")]
SqlitePath,
#[error("invalid {0} database URL")]
Url(&'static str),
}
+218
View File
@@ -0,0 +1,218 @@
use std::{collections::BTreeMap, path::Path};
use serde::Deserialize;
use serde::de::DeserializeOwned;
use thiserror::Error;
use crate::{
Address, ConfigError, DOCUMENTS, DeploymentConfig, ObjectStorage, Resource, SqlCluster,
};
#[derive(Clone, Copy, Debug)]
pub enum ConfigFormat {
Yaml,
Toml,
/// Compatibility with previously published deployment files.
Json,
}
#[derive(Clone, Copy, Debug)]
pub enum ImportFormat {
Catalog(ConfigFormat),
/// The bedrock_resources output of terraform output -json.
TerraformOutputs,
/// A ConfigMap carrying a catalog in data["bedrock-resources.yaml"].
KubernetesConfigMap,
}
#[derive(Debug, Error)]
pub enum FormatError {
#[error("configuration filename must end in .yaml, .yml, .toml or .json")]
FileExtension,
#[error("could not read the deployment configuration: {0}")]
Io(#[from] std::io::Error),
// Parser errors may quote connection strings or credentials.
#[error("invalid {0} configuration document")]
Parse(&'static str),
#[error("could not serialize the deployment configuration as YAML")]
Serialize,
#[error("import does not contain a Bedrock resource catalog")]
MissingCatalog,
#[error("publishable deployment configuration requires a valid catalog: {0}")]
Config(#[from] ConfigError),
}
impl ConfigFormat {
fn parse<T: DeserializeOwned>(self, input: &str) -> Result<T, FormatError> {
match self {
Self::Yaml => serde_saphyr::from_str(input).map_err(|_| FormatError::Parse("YAML")),
Self::Toml => toml::from_str(input).map_err(|_| FormatError::Parse("TOML")),
Self::Json => serde_json::from_str(input).map_err(|_| FormatError::Parse("JSON")),
}
}
}
impl DeploymentConfig {
pub fn parse(input: &str, format: ConfigFormat) -> Result<Self, FormatError> {
format
.parse::<DeploymentInput>(input)?
.try_into()
.map_err(Into::into)
}
pub fn load(path: impl AsRef<Path>) -> Result<Self, FormatError> {
let path = path.as_ref();
let format = match path.extension().and_then(|value| value.to_str()) {
Some("yaml" | "yml") => ConfigFormat::Yaml,
Some("toml") => ConfigFormat::Toml,
Some("json") => ConfigFormat::Json,
_ => return Err(FormatError::FileExtension),
};
Self::parse(&std::fs::read_to_string(path)?, format)
}
/// Serializes the configuration, including any credentials in connection strings.
pub fn to_yaml(&self) -> Result<String, FormatError> {
self.resolve()?;
serde_saphyr::to_string(self).map_err(|_| FormatError::Serialize)
}
/// Imports an inventory atomically. Deployment roles are assigned separately.
pub fn import_resources(
&mut self,
input: &str,
format: ImportFormat,
) -> Result<(), FormatError> {
let resources: BTreeMap<String, Resource> = match format {
ImportFormat::Catalog(format) => format.parse(input)?,
ImportFormat::TerraformOutputs => {
let exports: TerraformOutputs = ConfigFormat::Json.parse(input)?;
exports
.bedrock_resources
.ok_or(FormatError::MissingCatalog)?
.value
}
ImportFormat::KubernetesConfigMap => {
let manifest: ConfigMap = ConfigFormat::Yaml.parse(input)?;
if manifest.kind != "ConfigMap" || manifest.api_version != "v1" {
return Err(FormatError::MissingCatalog);
}
let catalog = manifest
.data
.get("bedrock-resources.yaml")
.ok_or(FormatError::MissingCatalog)?;
ConfigFormat::Yaml.parse(catalog)?
}
};
let mut candidate = self.clone();
for (name, resource) in resources {
candidate.insert_resource(name, resource)?;
}
*self = candidate;
Ok(())
}
}
// Compatibility for the older, category-specific on-disk layout. Normalize once on load.
#[derive(Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub(crate) struct DeploymentInput {
deployment: Option<String>,
config_version: Option<String>,
resources: BTreeMap<String, Resource>,
bindings: BTreeMap<String, String>,
read_only: bool,
cluster: Option<String>,
clusters: BTreeMap<String, SqlCluster>,
sql: BTreeMap<String, String>,
object_storage: BTreeMap<String, ObjectStorage>,
sqlite_path: Option<Address>,
}
impl TryFrom<DeploymentInput> for DeploymentConfig {
type Error = ConfigError;
fn try_from(input: DeploymentInput) -> Result<Self, Self::Error> {
let defaults = Self::default();
let mut config = Self {
deployment: input.deployment.unwrap_or(defaults.deployment),
config_version: input.config_version.unwrap_or(defaults.config_version),
resources: input.resources,
bindings: input.bindings,
read_only: input.read_only,
};
let has_canonical_config = !config.resources.is_empty() || !config.bindings.is_empty();
let has_legacy_sql_targets = !input.clusters.is_empty();
for (name, resource) in input
.clusters
.into_iter()
.map(|(name, cluster)| (name, Resource::Sql(cluster)))
.chain(
input
.object_storage
.into_iter()
.map(|(name, store)| (name, Resource::ObjectStore(store))),
)
{
if config.resources.insert(name, resource).is_some() {
return Err(ConfigError::DuplicateResource);
}
}
let mut sql = input.sql;
if let Some(name) = input.cluster {
if sql.get(DOCUMENTS).is_some_and(|target| target != &name) {
return Err(ConfigError::ConflictingDocuments);
}
sql.insert(DOCUMENTS.into(), name);
}
if !has_canonical_config && has_legacy_sql_targets && sql.is_empty() {
return Err(ConfigError::ClusterRequired);
}
for (role, target) in sql {
if !matches!(config.resources.get(&target), Some(Resource::Sql(_))) {
return Err(ConfigError::UnknownCluster);
}
if config
.bindings
.get(&role)
.is_some_and(|existing| existing != &target)
{
return Err(ConfigError::ConflictingBinding(role));
}
config.bindings.insert(role, target);
}
if !has_canonical_config
&& config.bindings.is_empty()
&& (input.sqlite_path.is_some() || !config.resources.is_empty())
{
let mut name = String::from("local");
while config.resources.contains_key(&name) {
name.push('-');
}
let local = input
.sqlite_path
.map_or_else(Resource::default_documents, Resource::local_documents);
config.resources.insert(name.clone(), local);
config.bindings.insert(DOCUMENTS.into(), name);
}
Ok(config)
}
}
#[derive(Deserialize)]
struct TerraformOutputs {
bedrock_resources: Option<TerraformOutput>,
}
#[derive(Deserialize)]
struct TerraformOutput {
value: BTreeMap<String, Resource>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct ConfigMap {
api_version: String,
kind: String,
data: BTreeMap<String, String>,
}
+126
View File
@@ -0,0 +1,126 @@
//! Runtime configuration and named backend resources for Bedrock.
mod catalog;
mod driver;
mod error;
mod format;
mod object_storage;
mod resource;
mod sql;
mod transport;
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
pub use driver::*;
pub use error::ConfigError;
pub use format::{ConfigFormat, FormatError, ImportFormat};
pub use object_storage::ObjectStorage;
pub use resource::{ResolvedResource, Resource, ResourceRef};
/// Compatibility name for the SQL cluster configuration.
pub use sql::SqlCluster as Cluster;
pub use sql::{ResolvedSql, SqlCluster};
pub use transport::{Address, Tls};
pub const DOCUMENTS: &str = "documents";
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(try_from = "format::DeploymentInput")]
pub struct DeploymentConfig {
pub deployment: String,
pub config_version: String,
pub resources: BTreeMap<String, Resource>,
/// Role to named resource.
pub bindings: BTreeMap<String, String>,
pub read_only: bool,
}
impl Default for DeploymentConfig {
fn default() -> Self {
Self {
deployment: "default".into(),
config_version: "local".into(),
resources: BTreeMap::new(),
bindings: BTreeMap::new(),
read_only: false,
}
}
}
/// A validated startup snapshot. The version identifies the configuration release.
#[derive(Clone, Debug)]
pub struct ResolvedDeployment {
pub deployment: String,
pub config_version: String,
resources: BTreeMap<String, ResolvedResource>,
bindings: BTreeMap<String, String>,
}
impl ResolvedDeployment {
pub fn resource(&self, name: &str) -> Option<&ResolvedResource> {
self.resources.get(name)
}
pub fn binding(&self, role: &str) -> Option<&ResolvedResource> {
self.resource(self.bindings.get(role)?)
}
pub fn bound_resources(&self) -> impl Iterator<Item = (&str, &ResolvedResource)> {
self.bindings
.iter()
.map(|(role, target)| (role.as_str(), &self.resources[target]))
}
}
impl DeploymentConfig {
pub fn resolve(&self) -> Result<ResolvedDeployment, ConfigError> {
validate_name(&self.deployment, "deployment")?;
validate_name(&self.config_version, "config version")?;
let mut resources = BTreeMap::new();
let mut bindings = self.bindings.clone();
for (name, resource) in &self.resources {
validate_name(name, "resource")?;
resources.insert(
name.clone(),
resource.resolve(&self.deployment, Some(name), self.read_only)?,
);
}
if resources.is_empty() && bindings.is_empty() {
let default = Resource::default_documents();
resources.insert(
"local".into(),
default.resolve(&self.deployment, None, self.read_only)?,
);
bindings.insert(DOCUMENTS.into(), "local".into());
}
for (role, target) in &bindings {
validate_name(role, "role")?;
validate_name(target, "resource")?;
if !resources.contains_key(target) {
return Err(ConfigError::UnknownBinding {
role: role.clone(),
target: target.clone(),
});
}
}
Ok(ResolvedDeployment {
deployment: self.deployment.clone(),
config_version: self.config_version.clone(),
resources,
bindings,
})
}
}
pub(crate) fn validate_name(value: &str, kind: &'static str) -> Result<(), ConfigError> {
if value.is_empty()
|| value.len() > 128
|| !value
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b"-_.".contains(&b))
{
return Err(ConfigError::Name(kind));
}
Ok(())
}
+49
View File
@@ -0,0 +1,49 @@
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
ConfigError,
driver::ObjectStoreDriver,
transport::{Address, Tls},
};
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ObjectStorage {
pub driver: ObjectStoreDriver,
pub bucket: String,
pub region: String,
pub endpoint: Option<Address>,
}
impl ObjectStorage {
pub(crate) fn resolve(&self) -> Result<Self, ConfigError> {
if self.bucket.trim().is_empty() || self.region.trim().is_empty() {
return Err(ConfigError::ObjectStorage);
}
self.tls()?;
Ok(self.clone())
}
/// The TLS policy implied by this endpoint. The default S3 endpoint uses HTTPS.
pub fn tls(&self) -> Result<Tls, ConfigError> {
let Some(endpoint) = &self.endpoint else {
return Ok(Tls::VerifyFull);
};
let url =
Url::parse(endpoint.connection_string()).map_err(|_| ConfigError::ObjectStorage)?;
if url.host_str().is_none()
|| !url.username().is_empty()
|| url.password().is_some()
|| url.query().is_some()
|| url.fragment().is_some()
{
return Err(ConfigError::ObjectStorage);
}
match url.scheme() {
"https" => Ok(Tls::VerifyFull),
"http" => Ok(Tls::Disabled),
_ => Err(ConfigError::ObjectStorage),
}
}
}
+67
View File
@@ -0,0 +1,67 @@
//! Configurations and resolved settings dispatched by resource category.
use serde::{Deserialize, Serialize};
use crate::{Address, ConfigError, Driver, ObjectStorage, ResolvedSql, SqlCluster};
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Resource {
Sql(SqlCluster),
ObjectStore(ObjectStorage),
}
pub type ResourceRef<'a> = &'a Resource;
impl Resource {
pub fn driver(&self) -> Driver {
match self {
Self::Sql(cluster) => Driver::Sql(cluster.driver),
Self::ObjectStore(store) => Driver::ObjectStore(store.driver),
}
}
pub(crate) fn default_documents() -> Self {
Self::local_documents("bedrock.sqlite3".into())
}
pub(crate) fn local_documents(path: Address) -> Self {
Self::Sql(SqlCluster::local(path))
}
pub(crate) fn resolve(
&self,
deployment: &str,
name: Option<&str>,
read_only: bool,
) -> Result<ResolvedResource, ConfigError> {
match self {
Self::Sql(cluster) => cluster
.resolve(deployment, name, read_only)
.map(ResolvedResource::Sql),
Self::ObjectStore(store) => store.resolve().map(ResolvedResource::ObjectStore),
}
}
}
#[derive(Clone, Debug)]
pub enum ResolvedResource {
Sql(ResolvedSql),
ObjectStore(ObjectStorage),
}
impl ResolvedResource {
pub fn as_sql(&self) -> Option<&ResolvedSql> {
match self {
Self::Sql(sql) => Some(sql),
_ => None,
}
}
pub fn as_object_store(&self) -> Option<&ObjectStorage> {
match self {
Self::ObjectStore(store) => Some(store),
_ => None,
}
}
}
+138
View File
@@ -0,0 +1,138 @@
use std::path::Path;
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
ConfigError,
driver::SqlDriver,
transport::{Address, Tls},
};
/// A SQL target with a primary connection and optional read replicas.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct SqlCluster {
pub driver: SqlDriver,
pub primary: Address,
#[serde(default)]
pub replicas: Vec<Address>,
#[serde(default)]
pub tls: Tls,
#[serde(default = "default_pool_size")]
pub max_connections: u32,
}
const DEFAULT_POOL_SIZE: u32 = 5;
fn default_pool_size() -> u32 {
DEFAULT_POOL_SIZE
}
#[derive(Clone, Debug)]
pub struct ResolvedSql {
pub deployment: String,
pub cluster: Option<String>,
pub driver: SqlDriver,
pub primary: Address,
pub replicas: Vec<Address>,
pub read_only: bool,
pub max_connections: u32,
}
impl SqlCluster {
pub(crate) fn local(path: Address) -> Self {
Self {
driver: SqlDriver::Sqlite,
primary: path,
replicas: vec![],
tls: Tls::Disabled,
max_connections: 1,
}
}
pub(crate) fn resolve(
&self,
deployment: &str,
name: Option<&str>,
read_only: bool,
) -> Result<ResolvedSql, ConfigError> {
if self.max_connections == 0 {
return Err(ConfigError::PoolSize);
}
if self.driver == SqlDriver::Sqlite && !self.replicas.is_empty() {
return Err(ConfigError::SqliteReplicas);
}
let primary = resolve_address(self, &self.primary, read_only)?;
let replicas = self
.replicas
.iter()
.map(|address| resolve_address(self, address, true))
.collect::<Result<_, _>>()?;
Ok(ResolvedSql {
deployment: deployment.into(),
cluster: name.map(str::to_owned),
driver: self.driver,
primary,
replicas,
read_only,
max_connections: self.max_connections,
})
}
}
fn resolve_address(
cluster: &SqlCluster,
address: &Address,
read_only: bool,
) -> Result<Address, ConfigError> {
let address = address.connection_string();
let (driver, tls_key, tls_enabled, tls_disabled) = match cluster.driver {
SqlDriver::Sqlite => return sqlite_url(address, read_only),
SqlDriver::Postgres => ("postgres", "sslmode", "verify-full", "disable"),
SqlDriver::Mysql => ("mysql", "ssl-mode", "VERIFY_IDENTITY", "DISABLED"),
};
let mut url = Url::parse(address).map_err(|_| ConfigError::Url(driver))?;
let compatible = url.scheme() == driver || driver == "postgres" && url.scheme() == "postgresql";
if !compatible
|| url.host_str().is_none()
|| url.username().is_empty()
|| url.path().trim_matches('/').is_empty()
|| url.fragment().is_some()
|| url.query_pairs().any(|(key, _)| {
matches!(
key.as_ref(),
"sslmode"
| "ssl-mode"
| "host"
| "hostaddr"
| "port"
| "socket"
| "dbname"
| "options"
)
})
{
return Err(ConfigError::Url(driver));
}
let tls_mode = match cluster.tls {
Tls::VerifyFull => tls_enabled,
Tls::Disabled => tls_disabled,
};
url.query_pairs_mut().append_pair(tls_key, tls_mode);
Ok(Address::from(String::from(url)))
}
fn sqlite_url(path: &str, read_only: bool) -> Result<Address, ConfigError> {
if path.is_empty() || path == ":memory:" || path.contains('\0') {
return Err(ConfigError::SqlitePath);
}
let absolute = std::path::absolute(Path::new(path)).map_err(|_| ConfigError::SqlitePath)?;
let file = Url::from_file_path(absolute).map_err(|_| ConfigError::SqlitePath)?;
let file = file
.as_str()
.strip_prefix("file:")
.ok_or(ConfigError::SqlitePath)?;
let mode = if read_only { "ro" } else { "rwc" };
Ok(Address::from(format!("sqlite:{file}?mode={mode}")))
}
+43
View File
@@ -0,0 +1,43 @@
//! Address and TLS settings shared by backend configurations.
use std::fmt;
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Tls {
#[default]
VerifyFull,
Disabled,
}
/// A backend connection string, endpoint URL, or local path.
/// Debug output includes the full value, which may contain credentials.
#[derive(Clone, Deserialize, Serialize)]
#[serde(transparent)]
pub struct Address(String);
impl From<&str> for Address {
fn from(value: &str) -> Self {
Self(value.to_owned())
}
}
impl From<String> for Address {
fn from(value: String) -> Self {
Self(value)
}
}
impl fmt::Debug for Address {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.0, formatter)
}
}
impl Address {
pub fn connection_string(&self) -> &str {
&self.0
}
}
+263
View File
@@ -0,0 +1,263 @@
use std::collections::BTreeMap;
use clusters::{
Address, ConfigError, DOCUMENTS, DeploymentConfig, Resource, SqlCluster, SqlDriver, Tls,
};
#[test]
fn address_debug_formats_the_inner_string() {
let value = "bedrock.sqlite3";
assert_eq!(format!("{:?}", Address::from(value)), format!("{value:?}"));
}
#[test]
fn named_cluster_requires_matching_addresses() {
let mut config = DeploymentConfig {
bindings: BTreeMap::from([(DOCUMENTS.into(), "regional".into())]),
resources: BTreeMap::from([(
"regional".into(),
Resource::Sql(SqlCluster {
driver: SqlDriver::Postgres,
primary: "postgres://user:secret@primary/bedrock".into(),
replicas: vec!["postgresql://reader:secret@replica/bedrock".into()],
tls: Tls::VerifyFull,
max_connections: 5,
}),
)]),
..DeploymentConfig::default()
};
let resolved = config.resolve().unwrap();
let resolved = resolved.binding(DOCUMENTS).unwrap().as_sql().unwrap();
assert!(
resolved
.primary
.connection_string()
.ends_with("sslmode=verify-full")
);
assert!(
resolved.replicas[0]
.connection_string()
.ends_with("sslmode=verify-full")
);
let Some(Resource::Sql(cluster)) = config.resources.get_mut("regional") else {
panic!("expected a SQL resource");
};
cluster.replicas[0] = "mysql://user:secret@replica/bedrock".into();
assert!(matches!(
config.resolve(),
Err(ConfigError::Url("postgres"))
));
}
#[test]
fn resolves_named_connections_and_round_trips_yaml() {
use clusters::ConfigFormat;
let config = DeploymentConfig::parse(
include_str!("../../../deploy/kubernetes/multi-storage.yaml"),
ConfigFormat::Yaml,
)
.unwrap();
let snapshot = config.resolve().unwrap();
assert_eq!(snapshot.config_version, "example-1");
assert_eq!(
snapshot
.binding(DOCUMENTS)
.unwrap()
.as_sql()
.unwrap()
.driver,
SqlDriver::Postgres
);
assert_eq!(
snapshot.binding("legacy").unwrap().as_sql().unwrap().driver,
SqlDriver::Mysql
);
assert_eq!(
snapshot
.binding("attachments")
.unwrap()
.as_object_store()
.unwrap()
.bucket,
"bedrock-attachments"
);
assert_eq!(
snapshot
.binding(DOCUMENTS)
.unwrap()
.as_sql()
.unwrap()
.max_connections,
5
);
let serialized = config.to_yaml().unwrap();
let roundtrip = DeploymentConfig::parse(&serialized, ConfigFormat::Yaml)
.unwrap()
.resolve()
.unwrap();
assert_eq!(
roundtrip
.binding("legacy")
.unwrap()
.as_sql()
.unwrap()
.driver,
SqlDriver::Mysql
);
}
#[test]
fn imports_catalog_atomically_and_preserves_role_references() {
use clusters::{ConfigFormat, Driver, ImportFormat, ObjectStoreDriver};
let mut config =
DeploymentConfig::parse("config_version = 'test'", ConfigFormat::Toml).unwrap();
config
.import_resources(
include_str!("../../../deploy/kubernetes/kubernetes-catalog.yaml"),
ImportFormat::KubernetesConfigMap,
)
.unwrap();
config.bindings.insert(DOCUMENTS.into(), "pg-main".into());
config.bindings.insert("files".into(), "attachments".into());
let before = config.resource("attachments").unwrap().driver();
assert_eq!(before, Driver::ObjectStore(ObjectStoreDriver::S3));
assert!(matches!(
config.remove_resource("pg-main"),
Err(ConfigError::ResourceInUse)
));
let inventory = r#"{
"bedrock_resources": {
"value": {
"another-bucket": {"kind":"object_store","driver":"s3","bucket":"other","region":"us-east-1"},
"attachments": {"kind":"object_store","driver":"s3","bucket":"duplicate","region":"us-east-1"}
}
}
}"#;
assert!(
config
.import_resources(inventory, ImportFormat::TerraformOutputs)
.is_err()
);
assert!(config.resource("another-bucket").is_none());
assert!(matches!(
config.remove_resource("attachments"),
Err(ConfigError::ResourceInUse)
));
config.bindings.remove("files");
let Resource::ObjectStore(mut updated) = config.remove_resource("attachments").unwrap() else {
panic!("expected S3 configuration");
};
updated.bucket = "updated".into();
config
.insert_resource("attachments".into(), Resource::ObjectStore(updated.clone()))
.unwrap();
updated.bucket = "replaced".into();
config
.update_resource("attachments", Resource::ObjectStore(updated))
.unwrap();
assert_eq!(
config
.resolve()
.unwrap()
.resource("attachments")
.unwrap()
.as_object_store()
.unwrap()
.bucket,
"replaced"
);
}
#[test]
fn legacy_configuration_is_normalized_at_load() {
use clusters::ConfigFormat;
let config = DeploymentConfig::parse(
r#"{
"cluster":"east",
"clusters":{"east":{"driver":"postgres","primary":"postgres://u@primary/db"}},
"object_storage":{"files":{"driver":"s3","bucket":"files","region":"us-east-1"}}
}"#,
ConfigFormat::Json,
)
.unwrap();
let snapshot = config.resolve().unwrap();
assert_eq!(
snapshot
.binding(DOCUMENTS)
.unwrap()
.as_sql()
.unwrap()
.driver,
SqlDriver::Postgres
);
assert_eq!(
snapshot
.resource("files")
.unwrap()
.as_object_store()
.unwrap()
.bucket,
"files"
);
let config =
DeploymentConfig::parse("sqlite_path: custom.sqlite3", ConfigFormat::Yaml).unwrap();
let snapshot = config.resolve().unwrap();
let connection = snapshot.binding(DOCUMENTS).unwrap().as_sql().unwrap();
assert!(
connection
.primary
.connection_string()
.ends_with("/custom.sqlite3?mode=rwc")
);
}
#[test]
fn missing_binding_target_is_rejected_for_any_role() {
let mut config = DeploymentConfig::default();
config
.bindings
.insert("attachments".into(), "missing".into());
assert!(
matches!(config.resolve(), Err(ConfigError::UnknownBinding { role, target })
if role == "attachments" && target == "missing")
);
}
#[test]
fn s3_uses_shared_address_and_endpoint_tls() {
use clusters::{ConfigFormat, ObjectStorage};
let config = DeploymentConfig::parse(
include_str!("../../../deploy/kubernetes/multi-storage.yaml"),
ConfigFormat::Yaml,
)
.unwrap();
let Some(Resource::ObjectStore(store)) = config.resource("attachment-store") else {
panic!("expected object storage configuration");
};
assert_eq!(store.tls().unwrap(), Tls::VerifyFull);
for (url, expected) in [
("https://objects.example.test", Tls::VerifyFull),
("http://objects.example.test", Tls::Disabled),
] {
let store = ObjectStorage {
endpoint: Some(url.into()),
..store.clone()
};
assert_eq!(store.endpoint.as_ref().unwrap().connection_string(), url);
assert_eq!(store.tls().unwrap(), expected);
}
let store = ObjectStorage {
endpoint: Some("https://user@objects.example.test".into()),
..store.clone()
};
assert!(matches!(store.tls(), Err(ConfigError::ObjectStorage)));
}
+27
View File
@@ -0,0 +1,27 @@
[package]
name = "database"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
[dependencies]
clusters.workspace = true
deadpool-postgres.workspace = true
documents.workspace = true
mysql_async.workspace = true
rusqlite.workspace = true
rustls.workspace = true
rustls-pemfile.workspace = true
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
tokio = { workspace = true, features = ["sync", "time"] }
tokio-postgres.workspace = true
tokio-postgres-rustls.workspace = true
tokio-rusqlite.workspace = true
url.workspace = true
webpki-roots.workspace = true
[dev-dependencies]
tempfile.workspace = true
tokio.workspace = true
+171
View File
@@ -0,0 +1,171 @@
//! Driver-independent documents, revisions, validation and encoding.
use std::{collections::HashSet, time::Duration};
use serde_json::Value;
use thiserror::Error;
pub type Revision = i64;
pub type Result<T> = std::result::Result<T, Error>;
pub(crate) const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
#[derive(Debug, Error)]
pub enum Error {
#[error("invalid {0}")]
Invalid(&'static str),
#[error("the database connection failed")]
Connection,
#[error("SQLite operation failed: {0}")]
Sqlite(#[from] rusqlite::Error),
#[error("PostgreSQL operation failed: {0}")]
Postgres(#[from] tokio_postgres::Error),
#[error("MySQL operation failed: {0}")]
Mysql(#[from] mysql_async::Error),
#[error("invalid database row")]
InvalidRow,
#[error("document encoding failed: {0}")]
Encoding(#[from] serde_json::Error),
#[error("the connection is read-only")]
ReadOnly,
#[error("the deployment is missing or retired")]
MissingDeployment,
#[error("database is at revision {available}, requested revision {requested}")]
Behind {
requested: Revision,
available: Revision,
},
#[error("the write conflicts with the current revision or lease")]
WriteConflict,
#[error("the workspace document already exists")]
DocumentAlreadyExists,
#[error("lease is missing, expired, or belongs to another store")]
LeaseLost,
}
impl Error {
pub fn retry_on_primary(&self) -> bool {
match self {
Self::Connection | Self::MissingDeployment | Self::Behind { .. } => true,
Self::Postgres(error) => {
error.is_closed()
|| error.code().is_some_and(|code| {
code.code().starts_with("08")
|| matches!(code.code(), "57P01" | "57P03" | "42P01")
})
}
Self::Mysql(mysql_async::Error::Server(error)) => {
error.state.starts_with("08") || error.code == 1146
}
Self::Mysql(error) => error.is_fatal(),
_ => false,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Document {
pub revision: Revision,
pub value: Value,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Snapshot {
pub revision: Revision,
pub document: Option<Document>,
}
#[derive(Clone, Debug)]
pub struct Mutation {
pub collection: String,
pub id: String,
/// None writes a tombstone. Some(Value::Null) stores a JSON null.
pub value: Option<Value>,
}
pub(crate) type EncodedSnapshot = (Revision, Option<Revision>, Option<Vec<u8>>);
pub(crate) struct EncodedMutation<'a> {
pub collection: &'a [u8],
pub id: &'a [u8],
pub payload: Option<Vec<u8>>,
}
pub(crate) fn validate_read(collection: &str, id: &str, at: Option<Revision>) -> Result<()> {
validate_id(collection)?;
validate_id(id)?;
if at.is_some_and(|revision| revision < 0) {
return Err(Error::Invalid("snapshot revision"));
}
Ok(())
}
pub(crate) fn snapshot(row: Option<EncodedSnapshot>, at: Option<Revision>) -> Result<Snapshot> {
let (available, document_revision, payload) = row.ok_or(Error::MissingDeployment)?;
let revision = at.unwrap_or(available);
if revision > available {
return Err(Error::Behind {
requested: revision,
available,
});
}
let document = match (document_revision, payload) {
(Some(revision), Some(payload)) => Some(Document {
revision,
value: serde_json::from_slice(&payload)?,
}),
_ => None,
};
Ok(Snapshot { revision, document })
}
pub(crate) fn encode_batch(
expected: Revision,
mutations: &[Mutation],
) -> Result<(Revision, Vec<EncodedMutation<'_>>)> {
let revision = expected
.checked_add(1)
.filter(|_| expected >= 0)
.ok_or(Error::Invalid("expected revision"))?;
if mutations.is_empty() {
return Err(Error::Invalid("empty write batch"));
}
let mut seen = HashSet::with_capacity(mutations.len());
let mut rows = Vec::with_capacity(mutations.len());
for mutation in mutations {
validate_id(&mutation.collection)?;
validate_id(&mutation.id)?;
if !seen.insert((&mutation.collection, &mutation.id)) {
return Err(Error::Invalid("duplicate document in write batch"));
}
rows.push(EncodedMutation {
collection: mutation.collection.as_bytes(),
id: mutation.id.as_bytes(),
payload: mutation
.value
.as_ref()
.map(serde_json::to_vec)
.transpose()?,
});
}
Ok((revision, rows))
}
pub(crate) fn validate_id(value: &str) -> Result<()> {
if value.is_empty() || value.len() > 128 || value.contains('\0') {
return Err(Error::Invalid(
"identifier (expected 1–128 bytes without NUL)",
));
}
Ok(())
}
// A single statement observes the revision and the document at the same point in time.
pub(crate) const GET_DOCUMENT: &str = "
SELECT d.revision, v.revision, v.payload
FROM bedrock_deployments d
LEFT JOIN bedrock_documents v
ON v.deployment = d.deployment AND v.collection = ? AND v.document_id = ?
AND v.revision <= COALESCE(?, d.revision)
WHERE d.deployment = ? AND d.retired = 0
ORDER BY v.revision DESC LIMIT 1";
+217
View File
@@ -0,0 +1,217 @@
//! Deployment bootstrap and read routing.
use std::sync::atomic::{AtomicUsize, Ordering};
use clusters::{
Address, ConfigError, DOCUMENTS, DeploymentConfig, ResolvedDeployment, ResolvedSql,
SqlDriver as Driver,
};
use thiserror::Error;
use crate::{
common::{Error as StorageError, Mutation, Revision, Snapshot},
mysql::{self, MySql, MySqlReader},
postgres::{self, Postgres, PostgresReader},
sqlite::{self, Sqlite, SqliteReader},
};
#[derive(Debug, Error)]
pub enum ConnectError {
#[error(transparent)]
Config(#[from] ConfigError),
#[error("the documents SQL role is not configured")]
MissingDocuments,
#[error("the documents role must reference a SQL resource")]
InvalidDocuments,
#[error(transparent)]
Storage(#[from] StorageError),
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ReadPreference {
/// Read from the primary endpoint.
#[default]
Primary,
/// Try configured replicas in round-robin order, then fall back to the primary.
/// Without an explicit snapshot revision a replica may return stale data.
PreferReplica,
}
/// A reader backed by the configured database. It exposes no raw SQL connection.
#[derive(Clone)]
pub enum Reader {
Sqlite(SqliteReader),
Postgres(PostgresReader),
Mysql(MySqlReader),
}
impl Reader {
pub async fn revision(&self) -> Result<Revision, StorageError> {
match self {
Self::Sqlite(reader) => reader.revision().await,
Self::Postgres(reader) => reader.revision().await,
Self::Mysql(reader) => reader.revision().await,
}
}
pub async fn get(
&self,
collection: &str,
id: &str,
at: Option<Revision>,
) -> Result<Snapshot, StorageError> {
match self {
Self::Sqlite(reader) => reader.get(collection, id, at).await,
Self::Postgres(reader) => reader.get(collection, id, at).await,
Self::Mysql(reader) => reader.get(collection, id, at).await,
}
}
}
#[derive(Clone)]
pub enum Store {
Sqlite(Sqlite),
Postgres(Postgres),
Mysql(MySql),
}
impl Store {
pub fn reader(&self) -> Reader {
match self {
Self::Sqlite(store) => Reader::Sqlite(store.reader()),
Self::Postgres(store) => Reader::Postgres(store.reader()),
Self::Mysql(store) => Reader::Mysql(store.reader()),
}
}
pub async fn commit(
&self,
expected: Revision,
changes: &[Mutation],
) -> Result<Revision, StorageError> {
match self {
Self::Sqlite(store) => store.commit(expected, changes).await,
Self::Postgres(store) => store.commit(expected, changes).await,
Self::Mysql(store) => store.commit(expected, changes).await,
}
}
}
pub struct Connection {
driver: Driver,
writer: Option<Store>,
primary: Reader,
replicas: Vec<Reader>,
next_replica: AtomicUsize,
}
pub async fn connect(config: &DeploymentConfig) -> Result<Connection, ConnectError> {
connect_resolved(&config.resolve()?).await
}
pub async fn connect_resolved(config: &ResolvedDeployment) -> Result<Connection, ConnectError> {
let resource = config
.binding(DOCUMENTS)
.ok_or(ConnectError::MissingDocuments)?;
connect_sql(resource.as_sql().ok_or(ConnectError::InvalidDocuments)?).await
}
pub async fn connect_sql(config: &ResolvedSql) -> Result<Connection, ConnectError> {
let writer = if config.read_only {
None
} else {
let url = config.primary.connection_string();
let name = &config.deployment;
let max = config.max_connections;
Some(match config.driver {
Driver::Sqlite => Store::Sqlite(sqlite::connect(url, name).await?),
Driver::Postgres => Store::Postgres(postgres::connect(url, name, max).await?),
Driver::Mysql => Store::Mysql(MySql::connect(url, name, max).await?),
})
};
let primary = match &writer {
Some(store) => store.reader(),
None => {
let reader = reader(config, &config.primary)?;
reader.revision().await?;
reader
}
};
let replicas = config
.replicas
.iter()
.map(|address| reader(config, address))
.collect::<Result<_, _>>()?;
Ok(Connection {
driver: config.driver,
writer,
primary,
replicas,
next_replica: AtomicUsize::new(0),
})
}
fn reader(config: &ResolvedSql, address: &Address) -> Result<Reader, StorageError> {
let url = address.connection_string();
let name = &config.deployment;
match config.driver {
Driver::Sqlite => sqlite::reader(url, name).map(Reader::Sqlite),
Driver::Postgres => {
postgres::reader(url, name, config.max_connections).map(Reader::Postgres)
}
Driver::Mysql => mysql::reader(url, name, config.max_connections).map(Reader::Mysql),
}
}
impl Connection {
pub fn driver(&self) -> Driver {
self.driver
}
pub fn is_read_only(&self) -> bool {
self.writer.is_none()
}
pub async fn revision(&self) -> Result<Revision, StorageError> {
self.primary.revision().await
}
pub async fn get(
&self,
collection: &str,
id: &str,
at: Option<Revision>,
preference: ReadPreference,
) -> Result<Snapshot, StorageError> {
if preference == ReadPreference::PreferReplica && !self.replicas.is_empty() {
let count = self.replicas.len();
let start = self.next_replica.fetch_add(1, Ordering::Relaxed) % count;
for replica in self.replicas.iter().cycle().skip(start).take(count) {
match replica.get(collection, id, at).await {
Ok(snapshot) => return Ok(snapshot),
Err(error) if error.retry_on_primary() => {}
Err(error) => return Err(error),
}
}
}
self.primary.get(collection, id, at).await
}
pub async fn commit(
&self,
expected: Revision,
changes: &[Mutation],
) -> Result<Revision, StorageError> {
match &self.writer {
Some(store) => store.commit(expected, changes).await,
None => Err(StorageError::ReadOnly),
}
}
pub fn mysql_writer(&self) -> Option<&MySql> {
match &self.writer {
Some(Store::Mysql(store)) => Some(store),
_ => None,
}
}
}
+129
View File
@@ -0,0 +1,129 @@
//! Maps workspace documents onto the versioned SQL store.
//!
//! Within a deployment, the workspace selects a collection and the document ID selects
//! a row. The v2 JSON payload stores the parent, position, and typed content.
use ::documents::{Document, DocumentContent, DocumentId, DocumentKey};
use serde::{Deserialize, Serialize};
use crate::{Connection, Mutation, ReadPreference, Result, Revision, StorageError};
const COLLECTION_PREFIX: &str = "bedrock:workspace-documents:v2:";
const LEGACY_COLLECTION_PREFIX: &str = "bedrock:workspace-documents:v1:";
/// A logical document and the deployment revision at which it was last written.
#[derive(Debug, PartialEq)]
pub struct StoredDocument {
pub document: Document,
pub revision: Revision,
}
#[derive(Deserialize, Serialize)]
struct DocumentPayload {
parent_id: Option<String>,
position: u64,
content: DocumentContent,
}
impl Connection {
/// Creates a document using the primary snapshot and its expected revision.
pub async fn create_document(&self, document: Document) -> Result<Revision> {
if self.is_read_only() {
return Err(StorageError::ReadOnly);
}
let (revision, existing) = self.lookup_document(&document.key, None).await?;
if existing.is_some() {
return Err(StorageError::DocumentAlreadyExists);
}
if let Some(parent) = &document.parent_id {
let parent_key = DocumentKey {
workspace: document.key.workspace.clone(),
document: parent.clone(),
};
let (_, stored) = self.lookup_document(&parent_key, Some(revision)).await?;
if stored.is_none() {
return Err(StorageError::Invalid("document parent"));
}
}
let value = serde_json::to_value(DocumentPayload {
parent_id: document.parent_id.map(|id| id.as_str().to_owned()),
position: document.position,
content: document.content,
})?;
self.commit(
revision,
&[Mutation {
collection: collection(COLLECTION_PREFIX, &document.key),
id: document.key.document.as_str().to_owned(),
value: Some(value),
}],
)
.await
}
/// Reads the latest state of a workspace document from the primary.
pub async fn get_document(&self, key: &DocumentKey) -> Result<Option<StoredDocument>> {
let (_, document) = self.lookup_document(key, None).await?;
Ok(document)
}
async fn lookup_document(
&self,
key: &DocumentKey,
at: Option<Revision>,
) -> Result<(Revision, Option<StoredDocument>)> {
let id = key.document.as_str();
let snapshot = self
.get(
&collection(COLLECTION_PREFIX, key),
id,
at,
ReadPreference::Primary,
)
.await?;
let revision = snapshot.revision;
if let Some(stored) = snapshot.document {
let payload: DocumentPayload = serde_json::from_value(stored.value)?;
let parent_id = payload
.parent_id
.map(DocumentId::new)
.transpose()
.map_err(|_| StorageError::Invalid("stored document parent ID"))?;
return Ok((
revision,
Some(StoredDocument {
document: Document {
key: key.clone(),
parent_id,
position: payload.position,
content: payload.content,
},
revision: stored.revision,
}),
));
}
// Use the same snapshot when looking up a document saved with the original encoding.
let legacy = self
.get(
&collection(LEGACY_COLLECTION_PREFIX, key),
id,
Some(revision),
ReadPreference::Primary,
)
.await?;
Ok((
revision,
legacy.document.map(|stored| StoredDocument {
document: Document::new(key.clone(), DocumentContent::Json(stored.value)),
revision: stored.revision,
}),
))
}
}
fn collection(prefix: &str, key: &DocumentKey) -> String {
format!("{prefix}{}", key.workspace.as_str())
}
+20
View File
@@ -0,0 +1,20 @@
//! Bedrock's transactional document storage for SQL databases.
mod common;
mod connection;
mod documents;
pub mod mysql;
pub mod postgres;
pub mod sqlite;
pub use self::documents::StoredDocument;
pub use clusters::SqlDriver as Dialect;
pub use clusters::{
Address, Cluster, ConfigError, DeploymentConfig, Resource, SqlCluster, SqlDriver as Driver, Tls,
};
pub use common::Error as StorageError;
pub use common::{Document, Error, Mutation, Result, Revision, Snapshot};
pub use connection::{
ConnectError, Connection, ReadPreference, Reader, Store, connect, connect_resolved, connect_sql,
};
pub use mysql::{Lease, MySql};
+412
View File
@@ -0,0 +1,412 @@
//! MySQL storage, writer leases and deployment cleanup.
use std::{fmt::Write, path::PathBuf, sync::Arc, time::Duration};
use mysql_async::{
ClientIdentity, Conn, Opts, OptsBuilder, Pool, PoolConstraints, PoolOpts, Row, SslOpts, TxOpts,
from_row_opt, prelude::Queryable,
};
use url::Url;
use crate::common::{
CONNECT_TIMEOUT, Error, GET_DOCUMENT, Mutation, Result, Revision, Snapshot, encode_batch,
snapshot, validate_id, validate_read,
};
const MYSQL_NOW: &str = "CAST(UNIX_TIMESTAMP(CURRENT_TIMESTAMP(3)) * 1000 AS SIGNED)";
const SCHEMA: &[&str] = &[
"CREATE TABLE IF NOT EXISTS bedrock_deployments (
deployment VARBINARY(128) PRIMARY KEY,
revision BIGINT NOT NULL DEFAULT 0,
retired BIGINT NOT NULL DEFAULT 0,
lease_epoch BIGINT NOT NULL DEFAULT 0,
lease_until BIGINT NOT NULL DEFAULT 0
) ENGINE=InnoDB",
"CREATE TABLE IF NOT EXISTS bedrock_documents (
deployment VARBINARY(128) NOT NULL,
collection VARBINARY(128) NOT NULL,
document_id VARBINARY(128) NOT NULL,
revision BIGINT NOT NULL,
payload LONGBLOB,
PRIMARY KEY (deployment, collection, document_id, revision),
FOREIGN KEY (deployment) REFERENCES bedrock_deployments(deployment)
) ENGINE=InnoDB",
];
#[derive(Clone)]
pub struct MySql {
reader: MySqlReader,
identity: Arc<()>,
}
#[derive(Clone)]
pub struct MySqlReader {
pool: Pool,
deployment: Arc<[u8]>,
}
impl MySqlReader {
fn new(url: &str, deployment: &str, max_connections: u32, read_only: bool) -> Result<Self> {
validate_id(deployment)?;
Ok(Self {
pool: Pool::new(connection_options(url, max_connections, read_only)?),
deployment: Arc::from(deployment.as_bytes()),
})
}
async fn connection(&self) -> Result<Conn> {
tokio::time::timeout(CONNECT_TIMEOUT, self.pool.get_conn())
.await
.map_err(|_| Error::Connection)?
.map_err(|_| Error::Connection)
}
pub async fn revision(&self) -> Result<Revision> {
let row: Row = self
.connection()
.await?
.exec_first(
"SELECT revision FROM bedrock_deployments WHERE deployment = ? AND retired = 0",
(self.deployment.as_ref(),),
)
.await?
.ok_or(Error::MissingDeployment)?;
from_row_opt(row).map_err(|_| Error::InvalidRow)
}
pub async fn get(&self, collection: &str, id: &str, at: Option<Revision>) -> Result<Snapshot> {
validate_read(collection, id, at)?;
let row: Option<Row> = self
.connection()
.await?
.exec_first(
GET_DOCUMENT,
(
collection.as_bytes(),
id.as_bytes(),
at,
self.deployment.as_ref(),
),
)
.await?;
let row = row
.map(from_row_opt)
.transpose()
.map_err(|_| Error::InvalidRow)?;
snapshot(row, at)
}
}
/// The monotonically increasing epoch fences off holders whose lease expired.
#[derive(Debug)]
pub struct Lease {
epoch: i64,
issuer: Arc<()>,
}
impl Lease {
pub fn epoch(&self) -> i64 {
self.epoch
}
}
impl MySql {
pub async fn connect(url: &str, deployment: &str, max_connections: u32) -> Result<Self> {
let reader = MySqlReader::new(url, deployment, max_connections, false)?;
{
let mut connection = reader.connection().await?;
for ddl in SCHEMA {
connection.query_drop(*ddl).await?;
}
connection
.exec_drop(
"INSERT INTO bedrock_deployments (deployment) VALUES (?)
ON DUPLICATE KEY UPDATE revision = revision",
(reader.deployment.as_ref(),),
)
.await?;
}
reader.revision().await?;
Ok(Self {
reader,
identity: Arc::new(()),
})
}
pub fn reader(&self) -> MySqlReader {
self.reader.clone()
}
/// An ordinary write is allowed while no lease is active.
pub async fn commit(&self, expected: Revision, mutations: &[Mutation]) -> Result<Revision> {
self.commit_with_fence(expected, mutations, None).await
}
pub async fn commit_with_lease(
&self,
lease: &Lease,
expected: Revision,
mutations: &[Mutation],
) -> Result<Revision> {
self.commit_with_fence(expected, mutations, Some(self.epoch(lease)?))
.await
}
async fn commit_with_fence(
&self,
expected: Revision,
mutations: &[Mutation],
fence: Option<i64>,
) -> Result<Revision> {
let (revision, rows) = encode_batch(expected, mutations)?;
let deployment = self.reader.deployment.as_ref();
let mut connection = self.reader.connection().await?;
let mut transaction = connection.start_transaction(TxOpts::default()).await?;
lock_deployment(&mut transaction, deployment).await?;
transaction
.exec_drop(
format!(
"UPDATE bedrock_deployments SET revision = ?
WHERE deployment = ? AND revision = ? AND retired = 0
AND ((? IS NULL AND lease_until <= {MYSQL_NOW})
OR (lease_epoch = ? AND lease_until > {MYSQL_NOW}))"
),
(revision, deployment, expected, fence, fence),
)
.await?;
if transaction.affected_rows() != 1 {
return Err(Error::WriteConflict);
}
transaction.exec_batch(
"INSERT INTO bedrock_documents (deployment, collection, document_id, revision, payload)
VALUES (?, ?, ?, ?, ?)",
rows.into_iter().map(|row| (deployment, row.collection, row.id, revision, row.payload)),
).await?;
transaction.commit().await?;
Ok(revision)
}
/// Acquires an expired or unheld lease using the database clock.
pub async fn acquire_lease(&self, ttl: Duration) -> Result<Option<Lease>> {
let ttl = lease_millis(ttl)?;
let update = format!(
"
UPDATE bedrock_deployments
SET lease_epoch = lease_epoch + 1, lease_until = {MYSQL_NOW} + ?
WHERE deployment = ? AND retired = 0 AND lease_until <= {MYSQL_NOW}"
);
let deployment = self.reader.deployment.as_ref();
let mut connection = self.reader.connection().await?;
let mut transaction = connection.start_transaction(TxOpts::default()).await?;
lock_deployment(&mut transaction, deployment).await?;
transaction.exec_drop(update, (ttl, deployment)).await?;
if transaction.affected_rows() != 1 {
return Ok(None);
}
let epoch: i64 = transaction
.exec_first(
"SELECT lease_epoch FROM bedrock_deployments WHERE deployment = ?",
(deployment,),
)
.await?
.ok_or(Error::MissingDeployment)?;
transaction.commit().await?;
Ok(Some(Lease {
epoch,
issuer: self.identity.clone(),
}))
}
/// Extends an active lease from the current database time without shortening it.
pub async fn renew_lease(&self, lease: &Lease, ttl: Duration) -> Result<()> {
let epoch = self.epoch(lease)?;
let ttl = lease_millis(ttl)?;
let update = format!(
"
UPDATE bedrock_deployments
SET lease_until = GREATEST(lease_until + 1, {MYSQL_NOW} + ?)
WHERE deployment = ? AND retired = 0 AND lease_epoch = ? AND lease_until > {MYSQL_NOW}"
);
let deployment = self.reader.deployment.as_ref();
let mut connection = self.reader.connection().await?;
let mut transaction = connection.start_transaction(TxOpts::default()).await?;
lock_deployment(&mut transaction, deployment).await?;
transaction
.exec_drop(update, (ttl, deployment, epoch))
.await?;
if transaction.affected_rows() != 1 {
return Err(Error::LeaseLost);
}
transaction.commit().await?;
Ok(())
}
pub async fn release_lease(&self, lease: &Lease) -> Result<bool> {
let epoch = self.epoch(lease)?;
let mut connection = self.reader.connection().await?;
connection
.exec_drop(
"UPDATE bedrock_deployments SET lease_until = 0
WHERE deployment = ? AND retired = 0 AND lease_epoch = ? AND lease_until > 0",
(self.reader.deployment.as_ref(), epoch),
)
.await?;
Ok(connection.affected_rows() == 1)
}
/// Removes only this deployment's documents and retires its identity in one transaction.
/// The retained deployment row prevents a restart from recreating the deleted deployment.
pub async fn delete_deployment(&self, lease: &Lease) -> Result<u64> {
let epoch = self.epoch(lease)?;
let update = format!(
"
UPDATE bedrock_deployments SET retired = 1, lease_until = 0
WHERE deployment = ? AND retired = 0 AND lease_epoch = ? AND lease_until > {MYSQL_NOW}"
);
let deployment = self.reader.deployment.as_ref();
let mut connection = self.reader.connection().await?;
let mut transaction = connection.start_transaction(TxOpts::default()).await?;
lock_deployment(&mut transaction, deployment).await?;
transaction.exec_drop(update, (deployment, epoch)).await?;
if transaction.affected_rows() != 1 {
return Err(Error::LeaseLost);
}
transaction
.exec_drop(
"DELETE FROM bedrock_documents WHERE deployment = ?",
(deployment,),
)
.await?;
let removed = transaction.affected_rows();
transaction.commit().await?;
Ok(removed)
}
fn epoch(&self, lease: &Lease) -> Result<i64> {
if !Arc::ptr_eq(&self.identity, &lease.issuer) {
return Err(Error::LeaseLost);
}
Ok(lease.epoch)
}
}
pub fn reader(url: &str, deployment: &str, max_connections: u32) -> Result<MySqlReader> {
MySqlReader::new(url, deployment, max_connections, true)
}
// MySQL evaluates the clock at statement start. Take the lock before checking the lease.
async fn lock_deployment(
transaction: &mut mysql_async::Transaction<'_>,
deployment: &[u8],
) -> Result<()> {
let revision: Option<Revision> = transaction.exec_first(
"SELECT revision FROM bedrock_deployments WHERE deployment = ? AND retired = 0 FOR UPDATE",
(deployment,),
).await?;
revision.ok_or(Error::MissingDeployment)?;
Ok(())
}
fn connection_options(address: &str, max_connections: u32, read_only: bool) -> Result<Opts> {
if max_connections == 0 {
return Err(Error::Invalid("database pool size"));
}
let mut url = Url::parse(address).map_err(|_| Error::Connection)?;
let mut tls = true;
let (mut ca, mut cert, mut key) = (None, None, None);
let (mut charset, mut collation, mut timezone, mut cache_size) = (None, None, None, None);
for (name, value) in url.query_pairs() {
match name.as_ref() {
"sslmode" | "ssl-mode" => {
tls = match value.as_ref() {
"DISABLED" => false,
"VERIFY_IDENTITY" => true,
_ => return Err(Error::Connection),
}
}
"sslca" | "ssl-ca" => ca = Some(PathBuf::from(value.as_ref())),
"sslcert" | "ssl-cert" => cert = Some(PathBuf::from(value.as_ref())),
"sslkey" | "ssl-key" => key = Some(PathBuf::from(value.as_ref())),
"charset" => charset = Some(mysql_identifier(&value)?),
"collation" => collation = Some(mysql_identifier(&value)?),
"timezone" | "time-zone" => timezone = Some(value.into_owned()),
"statement-cache-capacity" => {
cache_size = Some(value.parse::<usize>().map_err(|_| Error::Connection)?)
}
_ => {}
}
}
url.set_query(None);
let mut setup = Vec::new();
if charset.is_some() || collation.is_some() {
let charset = charset.as_deref().unwrap_or("utf8mb4");
let names = match collation {
Some(collation) => format!("SET NAMES {charset} COLLATE {collation}"),
None => format!("SET NAMES {charset}"),
};
setup.push(names);
}
if let Some(timezone) = timezone {
// A hex literal preserves the configured value without interpolating SQL syntax.
let mut encoded = String::new();
for byte in timezone.as_bytes() {
write!(encoded, "{byte:02x}").expect("writing to a string cannot fail");
}
setup.push(format!("SET time_zone = X'{encoded}'"));
}
if read_only {
setup.push("SET SESSION TRANSACTION READ ONLY".into());
}
let constraints =
PoolConstraints::new(max_connections.min(8) as usize, max_connections as usize)
.ok_or(Error::Invalid("database pool size"))?;
let opts = Opts::from_url(url.as_str()).map_err(|_| Error::Connection)?;
let mut builder = OptsBuilder::from_opts(opts)
.prefer_socket(false)
.pool_opts(
PoolOpts::new()
.with_constraints(constraints)
.with_reset_connection(false),
)
.setup(setup);
if let Some(cache_size) = cache_size {
builder = builder.stmt_cache_size(cache_size);
}
if tls {
let mut ssl = SslOpts::default();
if let Some(ca) = ca {
ssl = ssl
.with_disable_built_in_roots(true)
.with_root_certs(vec![ca.into()]);
}
match (cert, key) {
(Some(cert), Some(key)) => {
ssl = ssl.with_client_identity(Some(ClientIdentity::new(cert.into(), key.into())))
}
(None, None) => {}
_ => return Err(Error::Connection),
}
builder = builder.ssl_opts(Some(ssl));
}
Ok(builder.into())
}
fn mysql_identifier(value: &str) -> Result<String> {
if value.is_empty()
|| !value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
{
return Err(Error::Connection);
}
Ok(format!("`{value}`"))
}
fn lease_millis(ttl: Duration) -> Result<i64> {
let millis = ttl.as_millis();
if millis == 0 || millis >= i64::MAX as u128 / 2 {
return Err(Error::Invalid("lease duration"));
}
Ok(millis as i64)
}
+273
View File
@@ -0,0 +1,273 @@
//! PostgreSQL connection pools and the Bedrock document layout.
use std::{fs::File, io::BufReader, path::PathBuf, sync::Arc};
use deadpool_postgres::{Manager, Pool, Runtime};
use rustls::{ClientConfig, RootCertStore};
use tokio_postgres::{Config, config::SslMode};
use tokio_postgres_rustls::MakeRustlsConnect;
use url::Url;
use crate::common::{
CONNECT_TIMEOUT, Error, Mutation, Result, Revision, Snapshot, encode_batch, snapshot,
validate_id, validate_read,
};
const SCHEMA: &[&str] = &[
"CREATE TABLE IF NOT EXISTS bedrock_deployments (
deployment BYTEA PRIMARY KEY,
revision BIGINT NOT NULL DEFAULT 0,
retired BIGINT NOT NULL DEFAULT 0
)",
"CREATE TABLE IF NOT EXISTS bedrock_documents (
deployment BYTEA NOT NULL REFERENCES bedrock_deployments(deployment),
collection BYTEA NOT NULL,
document_id BYTEA NOT NULL,
revision BIGINT NOT NULL,
payload BYTEA,
PRIMARY KEY (deployment, collection, document_id, revision)
)",
];
const GET_DOCUMENT: &str = "
SELECT d.revision, v.revision, v.payload
FROM bedrock_deployments d
LEFT JOIN bedrock_documents v
ON v.deployment = d.deployment AND v.collection = $1 AND v.document_id = $2
AND v.revision <= COALESCE($3, d.revision)
WHERE d.deployment = $4 AND d.retired = 0
ORDER BY v.revision DESC LIMIT 1";
#[derive(Clone)]
pub struct PostgresReader {
pool: Pool,
deployment: Arc<[u8]>,
}
#[derive(Clone)]
pub struct Postgres {
reader: PostgresReader,
}
pub async fn connect(url: &str, deployment: &str, max_connections: u32) -> Result<Postgres> {
let reader = PostgresReader::new(url, deployment, max_connections, false)?;
{
let mut client = reader.client().await?;
let transaction = client.transaction().await?;
// PostgreSQL catalog inserts can race even with IF NOT EXISTS.
transaction
.batch_execute("SELECT pg_advisory_xact_lock(1694199371)")
.await?;
for ddl in SCHEMA {
transaction.batch_execute(ddl).await?;
}
transaction
.execute(
"INSERT INTO bedrock_deployments (deployment) VALUES ($1)
ON CONFLICT (deployment) DO NOTHING",
&[&reader.deployment.as_ref()],
)
.await?;
transaction.commit().await?;
}
reader.revision().await?;
Ok(Postgres { reader })
}
pub fn reader(url: &str, deployment: &str, max_connections: u32) -> Result<PostgresReader> {
PostgresReader::new(url, deployment, max_connections, true)
}
impl PostgresReader {
fn new(url: &str, deployment: &str, max_connections: u32, read_only: bool) -> Result<Self> {
validate_id(deployment)?;
if max_connections == 0 {
return Err(Error::Invalid("database pool size"));
}
let (config, tls) = connection_options(url, read_only)?;
let manager = Manager::new(config, tls);
let pool = Pool::builder(manager)
.max_size(max_connections as usize)
.runtime(Runtime::Tokio1)
.wait_timeout(Some(CONNECT_TIMEOUT))
.create_timeout(Some(CONNECT_TIMEOUT))
.build()
.map_err(|_| Error::Connection)?;
Ok(Self {
pool,
deployment: Arc::from(deployment.as_bytes()),
})
}
async fn client(&self) -> Result<deadpool_postgres::Client> {
self.pool.get().await.map_err(|_| Error::Connection)
}
pub async fn revision(&self) -> Result<Revision> {
let client = self.client().await?;
let query = client
.prepare_cached(
"SELECT revision FROM bedrock_deployments WHERE deployment = $1 AND retired = 0",
)
.await?;
let row = client
.query_opt(&query, &[&self.deployment.as_ref()])
.await?
.ok_or(Error::MissingDeployment)?;
Ok(row.try_get(0)?)
}
pub async fn get(&self, collection: &str, id: &str, at: Option<Revision>) -> Result<Snapshot> {
validate_read(collection, id, at)?;
let client = self.client().await?;
let query = client.prepare_cached(GET_DOCUMENT).await?;
let row = client
.query_opt(
&query,
&[
&collection.as_bytes(),
&id.as_bytes(),
&at,
&self.deployment.as_ref(),
],
)
.await?
.map(|row| -> Result<_> { Ok((row.try_get(0)?, row.try_get(1)?, row.try_get(2)?)) })
.transpose()?;
snapshot(row, at)
}
}
impl Postgres {
pub fn reader(&self) -> PostgresReader {
self.reader.clone()
}
pub async fn commit(&self, expected: Revision, mutations: &[Mutation]) -> Result<Revision> {
let (revision, rows) = encode_batch(expected, mutations)?;
let deployment = self.reader.deployment.as_ref();
let mut client = self.reader.client().await?;
let transaction = client.transaction().await?;
let advance = transaction
.prepare_cached(
"UPDATE bedrock_deployments SET revision = $1
WHERE deployment = $2 AND revision = $3 AND retired = 0",
)
.await?;
if transaction
.execute(&advance, &[&revision, &deployment, &expected])
.await?
!= 1
{
return Err(Error::WriteConflict);
}
let insert = transaction.prepare_cached(
"INSERT INTO bedrock_documents (deployment, collection, document_id, revision, payload)
VALUES ($1, $2, $3, $4, $5)",
).await?;
for row in rows {
transaction
.execute(
&insert,
&[
&deployment,
&row.collection,
&row.id,
&revision,
&row.payload,
],
)
.await?;
}
transaction.commit().await?;
Ok(revision)
}
}
fn connection_options(address: &str, read_only: bool) -> Result<(Config, MakeRustlsConnect)> {
let mut url = Url::parse(address).map_err(|_| Error::Connection)?;
let mut mode = SslMode::Require;
let (mut ca, mut cert, mut key) = (None, None, None);
let mut parameters = Vec::new();
for (name, value) in url.query_pairs() {
match name.as_ref() {
"sslmode" | "ssl-mode" => {
mode = match value.as_ref() {
"disable" => SslMode::Disable,
// The rustls connector verifies both the certificate chain and hostname.
"verify-full" | "require" => SslMode::Require,
_ => return Err(Error::Connection),
};
}
"sslrootcert" | "ssl-root-cert" | "ssl-ca" => ca = Some(PathBuf::from(value.as_ref())),
"sslcert" | "ssl-cert" => cert = Some(PathBuf::from(value.as_ref())),
"sslkey" | "ssl-key" => key = Some(PathBuf::from(value.as_ref())),
"application_name" | "user" | "password" => {
parameters.push((name.into_owned(), value.into_owned()))
}
_ => {}
}
}
url.set_query(None);
if !parameters.is_empty() {
url.query_pairs_mut().extend_pairs(parameters);
}
let mut config: Config = url.as_str().parse().map_err(|_| Error::Connection)?;
config.ssl_mode(mode).connect_timeout(CONNECT_TIMEOUT);
if read_only {
config.options("-c default_transaction_read_only=on");
}
let tls = tls_config(mode, ca, cert, key)?;
Ok((config, MakeRustlsConnect::new(tls)))
}
fn tls_config(
mode: SslMode,
ca: Option<PathBuf>,
cert: Option<PathBuf>,
key: Option<PathBuf>,
) -> Result<ClientConfig> {
let open = |path| {
File::open(path)
.map(BufReader::new)
.map_err(|_| Error::Connection)
};
let mut roots = RootCertStore::empty();
if mode != SslMode::Disable {
if let Some(path) = ca {
let mut file = open(path)?;
let mut count = 0;
for cert in rustls_pemfile::certs(&mut file) {
roots
.add(cert.map_err(|_| Error::Connection)?)
.map_err(|_| Error::Connection)?;
count += 1;
}
if count == 0 {
return Err(Error::Connection);
}
} else {
roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
}
}
let builder =
ClientConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
.with_safe_default_protocol_versions()
.map_err(|_| Error::Connection)?
.with_root_certificates(roots);
match (mode, cert, key) {
(SslMode::Disable, _, _) | (_, None, None) => Ok(builder.with_no_client_auth()),
(_, Some(cert), Some(key)) => {
let chain = rustls_pemfile::certs(&mut open(cert)?)
.collect::<std::io::Result<Vec<_>>>()
.map_err(|_| Error::Connection)?;
let key = rustls_pemfile::private_key(&mut open(key)?)
.map_err(|_| Error::Connection)?
.ok_or(Error::Connection)?;
builder
.with_client_auth_cert(chain, key)
.map_err(|_| Error::Connection)
}
_ => Err(Error::Connection),
}
}
+206
View File
@@ -0,0 +1,206 @@
//! File-backed Bedrock storage for self-hosted deployments.
use std::sync::Arc;
use rusqlite::{OpenFlags, OptionalExtension, TransactionBehavior, params};
use tokio::sync::OnceCell;
use tokio_rusqlite::Connection;
use crate::common::{
CONNECT_TIMEOUT, Error, GET_DOCUMENT, Mutation, Result, Revision, Snapshot, encode_batch,
snapshot, validate_id, validate_read,
};
const SCHEMA: &[&str] = &[
"CREATE TABLE IF NOT EXISTS bedrock_deployments (
deployment BLOB PRIMARY KEY NOT NULL,
revision INTEGER NOT NULL DEFAULT 0,
retired INTEGER NOT NULL DEFAULT 0
)",
"CREATE TABLE IF NOT EXISTS bedrock_documents (
deployment BLOB NOT NULL,
collection BLOB NOT NULL,
document_id BLOB NOT NULL,
revision INTEGER NOT NULL,
payload BLOB,
PRIMARY KEY (deployment, collection, document_id, revision),
FOREIGN KEY (deployment) REFERENCES bedrock_deployments(deployment)
)",
];
#[derive(Clone)]
pub struct SqliteReader {
inner: Arc<Endpoint>,
}
struct Endpoint {
uri: String,
flags: OpenFlags,
deployment: Vec<u8>,
connection: OnceCell<Connection>,
}
#[derive(Clone)]
pub struct Sqlite {
reader: SqliteReader,
}
pub async fn connect(url: &str, deployment: &str) -> Result<Sqlite> {
let reader = SqliteReader::new(url, deployment, false)?;
let deployment = reader.inner.deployment.clone();
reader
.call(move |connection| {
let transaction =
connection.transaction_with_behavior(TransactionBehavior::Immediate)?;
for ddl in SCHEMA {
transaction.execute_batch(ddl)?;
}
transaction.execute(
"INSERT INTO bedrock_deployments (deployment) VALUES (?)
ON CONFLICT (deployment) DO NOTHING",
[deployment],
)?;
transaction.commit()?;
Ok(())
})
.await?;
reader.revision().await?;
Ok(Sqlite { reader })
}
pub fn reader(url: &str, deployment: &str) -> Result<SqliteReader> {
SqliteReader::new(url, deployment, true)
}
impl SqliteReader {
fn new(url: &str, deployment: &str, read_only: bool) -> Result<Self> {
validate_id(deployment)?;
let address = url.strip_prefix("sqlite:").ok_or(Error::Connection)?;
let address = address.strip_prefix("//").unwrap_or(address);
let mut flags = OpenFlags::SQLITE_OPEN_URI | OpenFlags::SQLITE_OPEN_NO_MUTEX;
let uri = if read_only {
flags |= OpenFlags::SQLITE_OPEN_READ_ONLY;
let (path, query) = address.split_once('?').unwrap_or((address, ""));
let options =
url::form_urlencoded::parse(query.as_bytes()).filter(|(key, _)| key != "mode");
let query = url::form_urlencoded::Serializer::new(String::new())
.extend_pairs(options)
.append_pair("mode", "ro")
.finish();
format!("file:{path}?{query}")
} else {
flags |= OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_CREATE;
if address == ":memory:" {
address.to_owned()
} else {
format!("file:{address}")
}
};
Ok(Self {
inner: Arc::new(Endpoint {
uri,
flags,
deployment: deployment.as_bytes().to_vec(),
connection: OnceCell::new(),
}),
})
}
async fn call<T: Send + 'static>(
&self,
operation: impl FnOnce(&mut rusqlite::Connection) -> Result<T> + Send + 'static,
) -> Result<T> {
let connection = self
.inner
.connection
.get_or_try_init(|| async {
let connection = Connection::open_with_flags(&self.inner.uri, self.inner.flags)
.await
.map_err(|_| Error::Connection)?;
connection
.call(|connection| {
connection.busy_timeout(CONNECT_TIMEOUT)?;
connection.pragma_update(None, "foreign_keys", "ON")?;
Ok(())
})
.await
.map_err(|_| Error::Connection)?;
Ok::<_, Error>(connection)
})
.await?;
connection
.call(move |connection| Ok(operation(connection)))
.await
.map_err(|_| Error::Connection)?
}
pub async fn revision(&self) -> Result<Revision> {
let deployment = self.inner.deployment.clone();
self.call(move |connection| {
connection
.prepare_cached(
"SELECT revision FROM bedrock_deployments WHERE deployment = ? AND retired = 0",
)?
.query_row([deployment], |row| row.get(0))
.optional()?
.ok_or(Error::MissingDeployment)
})
.await
}
pub async fn get(&self, collection: &str, id: &str, at: Option<Revision>) -> Result<Snapshot> {
validate_read(collection, id, at)?;
let collection = collection.as_bytes().to_vec();
let id = id.as_bytes().to_vec();
let deployment = self.inner.deployment.clone();
let row = self
.call(move |connection| {
Ok(connection
.prepare_cached(GET_DOCUMENT)?
.query_row(params![collection, id, at, deployment], |row| {
Ok((row.get(0)?, row.get(1)?, row.get(2)?))
})
.optional()?)
})
.await?;
snapshot(row, at)
}
}
impl Sqlite {
pub fn reader(&self) -> SqliteReader {
self.reader.clone()
}
pub async fn commit(&self, expected: Revision, mutations: &[Mutation]) -> Result<Revision> {
let (revision, rows) = encode_batch(expected, mutations)?;
let rows: Vec<_> = rows
.into_iter()
.map(|row| (row.collection.to_vec(), row.id.to_vec(), row.payload))
.collect();
let deployment = self.reader.inner.deployment.clone();
self.reader
.call(move |connection| {
let transaction = connection.transaction_with_behavior(TransactionBehavior::Immediate)?;
let advanced = transaction.prepare_cached(
"UPDATE bedrock_deployments SET revision = ?
WHERE deployment = ? AND revision = ? AND retired = 0",
)?.execute(params![revision, deployment, expected])?;
if advanced != 1 {
return Err(Error::WriteConflict);
}
{
let mut insert = transaction.prepare_cached(
"INSERT INTO bedrock_documents (deployment, collection, document_id, revision, payload)
VALUES (?, ?, ?, ?, ?)",
)?;
for (collection, id, payload) in rows {
insert.execute(params![deployment, collection, id, revision, payload])?;
}
}
transaction.commit()?;
Ok(revision)
})
.await
}
}
+277
View File
@@ -0,0 +1,277 @@
use std::{collections::BTreeMap, env, time::Duration};
use database::{
Connection, DeploymentConfig, Driver, Mutation, ReadPreference, Resource, SqlCluster,
StorageError, Tls, connect,
};
use serde_json::json;
fn change(id: &str, text: &str) -> Mutation {
Mutation {
collection: "notes".into(),
id: id.into(),
value: Some(json!({ "text": text })),
}
}
fn sql_config(driver: Driver, url: &str, deployment: &str) -> DeploymentConfig {
DeploymentConfig {
deployment: deployment.into(),
bindings: BTreeMap::from([("documents".into(), "test".into())]),
resources: BTreeMap::from([(
"test".into(),
Resource::Sql(SqlCluster {
driver,
primary: url.into(),
replicas: vec![],
tls: Tls::Disabled,
max_connections: 4,
}),
)]),
..DeploymentConfig::default()
}
}
fn test_url(variable: &str) -> Option<String> {
match env::var(variable) {
Ok(url) => Some(url),
Err(_) if env::var_os("BEDROCK_REQUIRE_SQL_TESTS").is_some() => {
panic!("{variable} is required for the remote storage checks")
}
Err(_) => None,
}
}
async fn check_document_contract(db: &Connection) {
assert_eq!(db.revision().await.unwrap(), 0);
let original = change("doc", "first");
assert_eq!(db.commit(0, &[original]).await.unwrap(), 1);
let duplicate = [
change("other", "never written"),
change("other", "duplicate"),
];
assert!(matches!(
db.commit(1, &duplicate).await,
Err(StorageError::Invalid(_))
));
assert!(matches!(
db.commit(0, &[change("other", "stale")]).await,
Err(StorageError::WriteConflict)
));
let second = [change("doc", "second")];
let alternative = [change("doc", "alternative")];
let (one, two) = tokio::join!(db.commit(1, &second), db.commit(1, &alternative));
assert!(matches!(
(&one, &two),
(Ok(2), Err(StorageError::WriteConflict)) | (Err(StorageError::WriteConflict), Ok(2))
));
let old = db
.get("notes", "doc", Some(1), ReadPreference::Primary)
.await
.unwrap();
assert_eq!(old.document.unwrap().value, json!({ "text": "first" }));
assert!(matches!(
db.get("notes", "doc", Some(3), ReadPreference::Primary)
.await,
Err(StorageError::Behind {
requested: 3,
available: 2
})
));
assert!(
db.get("notes", "other", None, ReadPreference::Primary)
.await
.unwrap()
.document
.is_none()
);
let tombstone = Mutation {
collection: "notes".into(),
id: "doc".into(),
value: None,
};
let null_document = Mutation {
collection: "notes".into(),
id: "null".into(),
value: Some(json!(null)),
};
assert_eq!(db.commit(2, &[tombstone, null_document]).await.unwrap(), 3);
assert!(
db.get("notes", "doc", None, ReadPreference::Primary)
.await
.unwrap()
.document
.is_none()
);
let null_document = db
.get("notes", "null", None, ReadPreference::Primary)
.await
.unwrap();
assert_eq!(null_document.document.unwrap().value, json!(null));
}
#[tokio::test]
async fn sqlite_persists_across_reopening_and_enforces_read_only() {
let folder = tempfile::tempdir().unwrap();
let filename = folder.path().join("bedrock +?#%.sqlite");
let mut config = sql_config(Driver::Sqlite, filename.to_str().unwrap(), "default");
let db = connect(&config).await.unwrap();
assert_eq!(db.driver(), Driver::Sqlite);
check_document_contract(&db).await;
drop(db);
config.read_only = true;
let db = connect(&config).await.unwrap();
assert_eq!(db.revision().await.unwrap(), 3);
assert!(db.is_read_only());
assert!(matches!(
db.commit(3, &[change("doc", "invalid")]).await,
Err(StorageError::ReadOnly)
));
}
#[tokio::test]
async fn sqlite_read_only_startup_does_not_create_a_database() {
let folder = tempfile::tempdir().unwrap();
let filename = folder.path().join("missing.sqlite");
let mut config = sql_config(Driver::Sqlite, filename.to_str().unwrap(), "default");
config.read_only = true;
assert!(connect(&config).await.is_err());
assert!(!filename.exists());
}
#[tokio::test]
async fn postgres_reads_replicas_and_falls_back_when_behind() {
let Some(url) = test_url("BEDROCK_TEST_POSTGRES") else {
return;
};
let replica_url = test_url("BEDROCK_TEST_POSTGRES_REPLICA").unwrap();
let mut config = sql_config(Driver::Postgres, &url, "pg_contract");
let Some(Resource::Sql(cluster)) = config.resources.get_mut("test") else {
panic!("expected a SQL resource");
};
cluster.replicas.push(replica_url.clone().into());
let replica = connect(&sql_config(Driver::Postgres, &replica_url, "pg_contract"))
.await
.unwrap();
let (db, concurrent) = tokio::join!(connect(&config), connect(&config));
let db = db.unwrap();
assert_eq!(concurrent.unwrap().revision().await.unwrap(), 0);
check_document_contract(&db).await;
replica
.commit(0, &[change("doc", "replica")])
.await
.unwrap();
let stale = db
.get("notes", "doc", None, ReadPreference::PreferReplica)
.await
.unwrap();
assert_eq!(stale.revision, 1);
assert_eq!(stale.document.unwrap().value, json!({ "text": "replica" }));
let fresh = db
.get("notes", "null", Some(3), ReadPreference::PreferReplica)
.await
.unwrap();
assert_eq!(fresh.revision, 3);
assert_eq!(fresh.document.unwrap().value, json!(null));
config.read_only = true;
let db = connect(&config).await.unwrap();
assert!(db.is_read_only());
assert_eq!(db.revision().await.unwrap(), 3);
}
#[tokio::test]
async fn mysql_fences_writers_and_cleans_only_one_deployment() {
let Some(url) = test_url("BEDROCK_TEST_MYSQL") else {
return;
};
let config = sql_config(Driver::Mysql, &url, "mysql_contract");
let db = connect(&config).await.unwrap();
check_document_contract(&db).await;
let other = connect(&sql_config(Driver::Mysql, &url, "mysql_other"))
.await
.unwrap();
other.commit(0, &[change("doc", "keep")]).await.unwrap();
let mysql = db.mysql_writer().unwrap();
let lease = mysql
.acquire_lease(Duration::from_secs(30))
.await
.unwrap()
.unwrap();
assert!(
mysql
.acquire_lease(Duration::from_secs(30))
.await
.unwrap()
.is_none()
);
assert!(matches!(
db.commit(3, &[change("doc", "blocked")]).await,
Err(StorageError::WriteConflict)
));
assert!(matches!(
other
.mysql_writer()
.unwrap()
.delete_deployment(&lease)
.await,
Err(StorageError::LeaseLost)
));
mysql
.renew_lease(&lease, Duration::from_secs(30))
.await
.unwrap();
assert_eq!(
mysql
.commit_with_lease(&lease, 3, &[change("doc", "leased")])
.await
.unwrap(),
4
);
assert!(mysql.release_lease(&lease).await.unwrap());
let next = mysql
.acquire_lease(Duration::from_secs(30))
.await
.unwrap()
.unwrap();
assert!(next.epoch() > lease.epoch());
assert!(matches!(
mysql
.commit_with_lease(&lease, 4, &[change("doc", "stale")])
.await,
Err(StorageError::WriteConflict)
));
assert!(mysql.delete_deployment(&next).await.unwrap() > 0);
assert!(matches!(
db.revision().await,
Err(StorageError::MissingDeployment)
));
assert!(connect(&config).await.is_err());
assert_eq!(
other
.get("notes", "doc", None, ReadPreference::Primary)
.await
.unwrap()
.document
.unwrap()
.value,
json!({ "text": "keep" })
);
let mut other_config = sql_config(Driver::Mysql, &url, "mysql_other");
other_config.read_only = true;
assert_eq!(
connect(&other_config)
.await
.unwrap()
.revision()
.await
.unwrap(),
1
);
}
@@ -0,0 +1,135 @@
use std::{collections::BTreeMap, path::Path};
use database::{
DeploymentConfig, Driver, Mutation, Resource, SqlCluster, StorageError, Tls, connect,
};
use documents::{
Contextualize, Document, DocumentContent, DocumentId, DocumentKey, DocumentTree, WorkspaceId,
};
use serde_json::json;
fn document(workspace: &str, body: serde_json::Value) -> Document {
Document::new(
DocumentKey {
workspace: WorkspaceId::new(workspace).unwrap(),
document: DocumentId::new("same-id").unwrap(),
},
DocumentContent::Json(body),
)
}
fn sqlite_config(path: &Path) -> DeploymentConfig {
DeploymentConfig {
resources: BTreeMap::from([(
"local".into(),
Resource::Sql(SqlCluster {
driver: Driver::Sqlite,
primary: path.to_str().unwrap().into(),
replicas: vec![],
tls: Tls::Disabled,
max_connections: 1,
}),
)]),
bindings: BTreeMap::from([("documents".into(), "local".into())]),
..DeploymentConfig::default()
}
}
#[tokio::test]
async fn workspace_documents_keep_their_identity_and_contents_after_reopen() {
let folder = tempfile::tempdir().unwrap();
let path = folder.path().join("documents.sqlite3");
let mut config = sqlite_config(&path);
let connection = connect(&config).await.unwrap();
let first = document(
&"w".repeat(WorkspaceId::MAX_BYTES),
json!({"title": "notes"}),
);
let second = document("other-workspace", json!(null));
assert!(connection.get_document(&first.key).await.unwrap().is_none());
let first_revision = connection.create_document(first.clone()).await.unwrap();
let second_revision = connection.create_document(second.clone()).await.unwrap();
assert!(second_revision > first_revision);
assert!(matches!(
connection
.create_document(document(first.key.workspace.as_str(), json!("overwrite")))
.await,
Err(StorageError::DocumentAlreadyExists)
));
drop(connection);
config.read_only = true;
let connection = connect(&config).await.unwrap();
let read = connection.get_document(&first.key).await.unwrap().unwrap();
assert_eq!(read.document, first);
assert_eq!(read.revision, first_revision);
let read = connection.get_document(&second.key).await.unwrap().unwrap();
assert_eq!(read.document, second);
assert_eq!(read.revision, second_revision);
assert!(matches!(
connection
.create_document(document("third-workspace", json!(null)))
.await,
Err(StorageError::ReadOnly)
));
}
#[tokio::test]
async fn persists_typed_nodes_and_reads_the_original_json_encoding() {
let folder = tempfile::tempdir().unwrap();
let path = folder.path().join("documents.sqlite3");
let connection = connect(&sqlite_config(&path)).await.unwrap();
let page = Document::new(
document("team", json!(null)).key,
DocumentContent::Page {
title: "Planning".into(),
},
);
let mut todo = page.clone();
todo.key.document = DocumentId::new("todo").unwrap();
todo.parent_id = Some(page.key.document.clone());
todo.position = 2;
todo.content = DocumentContent::Todo {
text: "Review".into(),
checked: true,
};
assert!(matches!(
connection.create_document(todo.clone()).await,
Err(StorageError::Invalid("document parent"))
));
connection.create_document(page.clone()).await.unwrap();
connection.create_document(todo.clone()).await.unwrap();
let read = connection.get_document(&todo.key).await.unwrap().unwrap();
assert_eq!(read.document, todo);
let tree = DocumentTree::new(page, [read.document]).unwrap();
assert_eq!(tree.render_context(), "# Planning\n- [x] Review");
let legacy = document("legacy", json!({"previous": "body"}));
connection
.commit(
connection.revision().await.unwrap(),
&[Mutation {
collection: "bedrock:workspace-documents:v1:legacy".into(),
id: legacy.key.document.as_str().into(),
value: Some(json!({"previous": "body"})),
}],
)
.await
.unwrap();
assert_eq!(
connection
.get_document(&legacy.key)
.await
.unwrap()
.unwrap()
.document,
legacy
);
assert!(matches!(
connection.create_document(legacy).await,
Err(StorageError::DocumentAlreadyExists)
));
}
+10
View File
@@ -0,0 +1,10 @@
[package]
name = "documents"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
[dependencies]
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
+4
View File
@@ -0,0 +1,4 @@
/// Produces a textual description from already available data.
pub trait Contextualize {
fn render_context(&self) -> String;
}
+97
View File
@@ -0,0 +1,97 @@
use serde::{Deserialize, Serialize};
use serde_json::Value;
use super::contextualize::Contextualize;
use super::{
id::{IdError, validate_id},
rich_text::RichText,
workspace::WorkspaceId,
};
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct DocumentId(String);
impl DocumentId {
pub const MAX_BYTES: usize = 128;
pub fn new(value: impl Into<String>) -> Result<Self, IdError> {
let value = value.into();
validate_id(&value, Self::MAX_BYTES, IdError::Document)?;
Ok(Self(value))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
/// A document ID identifies a document within its workspace.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct DocumentKey {
pub workspace: WorkspaceId,
pub document: DocumentId,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Document {
pub key: DocumentKey,
pub parent_id: Option<DocumentId>,
pub position: u64,
pub content: DocumentContent,
}
impl Document {
pub fn new(key: DocumentKey, content: DocumentContent) -> Self {
Self {
key,
parent_id: None,
position: 0,
content,
}
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(tag = "kind", content = "data", rename_all = "snake_case")]
pub enum DocumentContent {
Page {
title: String,
},
Heading(RichText),
Paragraph(RichText),
ListItem(RichText),
Todo {
text: RichText,
checked: bool,
},
Code {
language: String,
source: String,
},
/// Preserves documents written with the original arbitrary JSON model.
Json(Value),
}
impl Contextualize for DocumentContent {
fn render_context(&self) -> String {
match self {
Self::Page { title } => format!("# {title}"),
Self::Heading(text) => format!("## {}", text.render_context()),
Self::Paragraph(text) => text.render_context(),
Self::ListItem(text) => format!("- {}", text.render_context()),
Self::Todo { text, checked } => {
let mark = if *checked { 'x' } else { ' ' };
format!("- [{mark}] {}", text.render_context())
}
Self::Code { language, source } => format!("Code ({language}):\n{source}"),
Self::Json(value) => value.to_string(),
}
}
}
impl Contextualize for Document {
fn render_context(&self) -> String {
self.content.render_context()
}
}
+20
View File
@@ -0,0 +1,20 @@
use thiserror::Error;
#[derive(Debug, Error, PartialEq, Eq)]
pub enum IdError {
#[error("a workspace ID must contain 1–96 bytes and no NUL")]
Workspace,
#[error("a document ID must contain 1–128 bytes and no NUL")]
Document,
#[error("a user ID must contain 1–128 bytes and no NUL")]
User,
#[error("an organization ID must contain 1–128 bytes and no NUL")]
Organization,
}
pub(super) fn validate_id(value: &str, max_bytes: usize, error: IdError) -> Result<(), IdError> {
if value.is_empty() || value.len() > max_bytes || value.contains('\0') {
return Err(error);
}
Ok(())
}
+19
View File
@@ -0,0 +1,19 @@
//! Logical models for documents, workspaces, users, and organizations.
mod contextualize;
mod document;
mod id;
mod organization;
mod rich_text;
mod tree;
mod user;
mod workspace;
pub use contextualize::Contextualize;
pub use document::{Document, DocumentContent, DocumentId, DocumentKey};
pub use id::IdError;
pub use organization::{Organization, OrganizationId, OrganizationMembership, OrganizationRole};
pub use rich_text::{Inline, RichText};
pub use tree::{DocumentTree, TreeError};
pub use user::{User, UserId};
pub use workspace::{Workspace, WorkspaceId};
+64
View File
@@ -0,0 +1,64 @@
use super::contextualize::Contextualize;
use super::{
id::{IdError, validate_id},
user::UserId,
};
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct OrganizationId(String);
impl OrganizationId {
pub const MAX_BYTES: usize = 128;
pub fn new(value: impl Into<String>) -> Result<Self, IdError> {
let value = value.into();
validate_id(&value, Self::MAX_BYTES, IdError::Organization)?;
Ok(Self(value))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Organization {
pub id: OrganizationId,
pub name: String,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum OrganizationRole {
Owner,
Admin,
Member,
}
/// Links a user to an organization with a role in that organization.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct OrganizationMembership {
pub organization_id: OrganizationId,
pub user_id: UserId,
pub role: OrganizationRole,
}
impl Contextualize for Organization {
fn render_context(&self) -> String {
format!("Organization: {}", self.name)
}
}
impl Contextualize for OrganizationMembership {
fn render_context(&self) -> String {
let role = match self.role {
OrganizationRole::Owner => "owner",
OrganizationRole::Admin => "admin",
OrganizationRole::Member => "member",
};
format!(
"User {} is a {role} of organization {}",
self.user_id.as_str(),
self.organization_id.as_str()
)
}
}
+38
View File
@@ -0,0 +1,38 @@
use serde::{Deserialize, Serialize};
use super::contextualize::Contextualize;
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(tag = "kind", content = "data", rename_all = "snake_case")]
pub enum Inline {
Text(String),
Link { label: String, url: String },
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
#[serde(transparent)]
pub struct RichText(pub Vec<Inline>);
impl From<&str> for RichText {
fn from(value: &str) -> Self {
Self(vec![Inline::Text(value.into())])
}
}
impl Contextualize for RichText {
fn render_context(&self) -> String {
let mut text = String::new();
for item in &self.0 {
match item {
Inline::Text(value) => text.push_str(value),
Inline::Link { label, url } => {
text.push_str(label);
text.push_str(" (");
text.push_str(url);
text.push(')');
}
}
}
text
}
}
+104
View File
@@ -0,0 +1,104 @@
use std::collections::{HashMap, HashSet};
use super::contextualize::Contextualize;
use thiserror::Error;
use crate::{Document, DocumentId};
#[derive(Debug, Error, PartialEq, Eq)]
pub enum TreeError {
#[error("all documents in the tree must belong to the same workspace")]
WorkspaceMismatch,
#[error("a document ID occurs more than once")]
DuplicateDocument,
#[error("the document tree has a missing parent or a cycle")]
InvalidParent,
}
/// An ordered view assembled from one page or content node and its descendants.
#[derive(Debug)]
pub struct DocumentTree {
root: Document,
descendants: Vec<(usize, Document)>,
}
impl DocumentTree {
pub fn new(
root: Document,
descendants: impl IntoIterator<Item = Document>,
) -> Result<Self, TreeError> {
let mut ids = HashSet::from([root.key.document.clone()]);
let mut by_parent: HashMap<DocumentId, Vec<Document>> = HashMap::new();
for document in descendants {
if document.key.workspace != root.key.workspace {
return Err(TreeError::WorkspaceMismatch);
}
if !ids.insert(document.key.document.clone()) {
return Err(TreeError::DuplicateDocument);
}
let parent = document.parent_id.clone().ok_or(TreeError::InvalidParent)?;
by_parent.entry(parent).or_default().push(document);
}
if root.parent_id.as_ref().is_some_and(|id| ids.contains(id)) {
return Err(TreeError::InvalidParent);
}
for siblings in by_parent.values_mut() {
// The ID breaks ties consistently when nodes have the same position.
siblings.sort_by(|a, b| {
a.position
.cmp(&b.position)
.then_with(|| a.key.document.as_str().cmp(b.key.document.as_str()))
});
}
let mut pending: Vec<_> = by_parent
.remove(&root.key.document)
.unwrap_or_default()
.into_iter()
.rev()
.map(|node| (1, node))
.collect();
let mut ordered = Vec::with_capacity(ids.len() - 1);
while let Some((depth, node)) = pending.pop() {
if let Some(children) = by_parent.remove(&node.key.document) {
pending.extend(children.into_iter().rev().map(|child| (depth + 1, child)));
}
ordered.push((depth, node));
}
if !by_parent.is_empty() {
return Err(TreeError::InvalidParent);
}
Ok(Self {
root,
descendants: ordered,
})
}
/// Traverses the root and descendants in display order, with their depth.
pub fn nodes(&self) -> impl Iterator<Item = (usize, &Document)> {
std::iter::once((0, &self.root))
.chain(self.descendants.iter().map(|(depth, node)| (*depth, node)))
}
}
impl Contextualize for DocumentTree {
fn render_context(&self) -> String {
let mut text = String::new();
let mut first_line = true;
for (depth, node) in self.nodes() {
let rendered = node.render_context();
for line in rendered.split('\n') {
if !first_line {
text.push('\n');
}
first_line = false;
for _ in 1..depth {
text.push_str(" ");
}
text.push_str(line);
}
}
text
}
}
+31
View File
@@ -0,0 +1,31 @@
use super::contextualize::Contextualize;
use super::id::{IdError, validate_id};
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct UserId(String);
impl UserId {
pub const MAX_BYTES: usize = 128;
pub fn new(value: impl Into<String>) -> Result<Self, IdError> {
let value = value.into();
validate_id(&value, Self::MAX_BYTES, IdError::User)?;
Ok(Self(value))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct User {
pub id: UserId,
pub display_name: String,
}
impl Contextualize for User {
fn render_context(&self) -> String {
format!("User: {}", self.display_name)
}
}
+36
View File
@@ -0,0 +1,36 @@
use super::contextualize::Contextualize;
use super::{
id::{IdError, validate_id},
organization::OrganizationId,
};
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct WorkspaceId(String);
impl WorkspaceId {
pub const MAX_BYTES: usize = 96;
pub fn new(value: impl Into<String>) -> Result<Self, IdError> {
let value = value.into();
validate_id(&value, Self::MAX_BYTES, IdError::Workspace)?;
Ok(Self(value))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
/// A workspace belongs to one organization and contains documents.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Workspace {
pub id: WorkspaceId,
pub organization_id: OrganizationId,
pub name: String,
}
impl Contextualize for Workspace {
fn render_context(&self) -> String {
format!("Workspace: {}", self.name)
}
}
+70
View File
@@ -0,0 +1,70 @@
use documents::{
Contextualize, Document, DocumentContent, DocumentId, DocumentKey, DocumentTree, TreeError,
WorkspaceId,
};
fn node(id: &str, parent: Option<&str>, position: u64, content: DocumentContent) -> Document {
Document {
key: DocumentKey {
workspace: WorkspaceId::new("workspace").unwrap(),
document: DocumentId::new(id).unwrap(),
},
parent_id: parent.map(|id| DocumentId::new(id).unwrap()),
position,
content,
}
}
#[test]
fn nested_pages_and_blocks_share_an_ordered_tree() {
let root = node(
"root",
None,
0,
DocumentContent::Page {
title: "Root".into(),
},
);
let page = node(
"page",
Some("root"),
2,
DocumentContent::Page {
title: "Nested".into(),
},
);
let paragraph = node(
"paragraph",
Some("page"),
0,
DocumentContent::Paragraph("Details".into()),
);
let heading = node(
"heading",
Some("root"),
1,
DocumentContent::Heading("Overview".into()),
);
let tree = DocumentTree::new(root, [paragraph, page, heading]).unwrap();
assert_eq!(
tree.nodes()
.map(|(depth, node)| (depth, node.key.document.as_str()))
.collect::<Vec<_>>(),
[(0, "root"), (1, "heading"), (1, "page"), (2, "paragraph")],
);
assert_eq!(
tree.render_context(),
"# Root\n## Overview\n# Nested\n Details"
);
}
#[test]
fn unreachable_cycle_is_rejected() {
let root = node("root", None, 0, DocumentContent::Paragraph("root".into()));
let a = node("a", Some("b"), 0, DocumentContent::Paragraph("a".into()));
let b = node("b", Some("a"), 0, DocumentContent::Paragraph("b".into()));
assert!(matches!(
DocumentTree::new(root, [a, b]),
Err(TreeError::InvalidParent)
));
}
-42
View File
@@ -1,42 +0,0 @@
BEGIN;
CREATE TABLE project_accounts (
project text NOT NULL,
id uuid NOT NULL,
google_subject text NOT NULL,
email text,
PRIMARY KEY (project, id),
UNIQUE (project, google_subject)
);
CREATE TABLE oauth_attempts (
state_hash text PRIMARY KEY,
browser_hash text NOT NULL,
project text NOT NULL,
frontend_challenge text NOT NULL,
google_verifier text NOT NULL,
expires_at timestamptz NOT NULL
);
CREATE TABLE login_grants (
token_hash text PRIMARY KEY,
project text NOT NULL,
account_id uuid NOT NULL,
frontend_challenge text NOT NULL,
expires_at timestamptz NOT NULL,
FOREIGN KEY (project, account_id) REFERENCES project_accounts (project, id) ON DELETE CASCADE
);
CREATE TABLE project_sessions (
token_hash text PRIMARY KEY,
project text NOT NULL,
account_id uuid NOT NULL,
expires_at timestamptz NOT NULL,
FOREIGN KEY (project, account_id) REFERENCES project_accounts (project, id) ON DELETE CASCADE
);
CREATE INDEX oauth_attempts_expiry ON oauth_attempts (expires_at);
CREATE INDEX login_grants_expiry ON login_grants (expires_at);
CREATE INDEX project_sessions_expiry ON project_sessions (expires_at);
COMMIT;
-224
View File
@@ -1,224 +0,0 @@
BEGIN;
-- Keep existing Google accounts and sessions valid during the expansion.
ALTER TABLE project_accounts ALTER COLUMN google_subject DROP NOT NULL;
ALTER TABLE project_accounts
ADD COLUMN username text,
ADD COLUMN display_name text NOT NULL DEFAULT '',
ADD COLUMN avatar_url text,
ADD COLUMN created_at timestamptz NOT NULL DEFAULT now(),
ADD COLUMN updated_at timestamptz NOT NULL DEFAULT now();
CREATE UNIQUE INDEX project_account_username ON project_accounts(project, lower(username))
WHERE username IS NOT NULL;
ALTER TABLE oauth_attempts
ADD COLUMN provider text NOT NULL DEFAULT 'google' CHECK (provider IN ('google','slack')),
ADD COLUMN oidc_nonce text;
CREATE TABLE account_identities (
project text NOT NULL,
provider text NOT NULL CHECK (provider IN ('google', 'slack')),
subject text NOT NULL,
account_id uuid NOT NULL,
PRIMARY KEY (project, provider, subject),
UNIQUE (project, provider, account_id),
FOREIGN KEY (project, account_id) REFERENCES project_accounts ON DELETE CASCADE
);
INSERT INTO account_identities(project, provider, subject, account_id)
SELECT project, 'google', google_subject, id FROM project_accounts WHERE google_subject IS NOT NULL;
CREATE TABLE email_credentials (
project text NOT NULL,
email text NOT NULL CHECK (email = lower(email)),
account_id uuid NOT NULL,
password_hash text NOT NULL,
verified_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (project, email),
UNIQUE (project, account_id),
FOREIGN KEY (project, account_id) REFERENCES project_accounts ON DELETE CASCADE
);
-- Registration is promoted to an account only after the single-use email check.
CREATE TABLE email_registrations (
project text NOT NULL,
email text NOT NULL,
password_hash text NOT NULL,
token_hash text NOT NULL UNIQUE,
expires_at timestamptz NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (project, email)
);
CREATE TABLE email_outbox (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
project text NOT NULL,
recipient text NOT NULL,
subject text NOT NULL,
body text NOT NULL,
attempts integer NOT NULL DEFAULT 0,
available_at timestamptz NOT NULL DEFAULT now(),
lease_until timestamptz,
lease_id uuid,
expires_at timestamptz NOT NULL,
sent_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX email_outbox_pending ON email_outbox(available_at) WHERE sent_at IS NULL;
CREATE TABLE auth_rate_limits (
key_hash text PRIMARY KEY,
attempts integer NOT NULL CHECK (attempts > 0),
expires_at timestamptz NOT NULL
);
CREATE TABLE onboarding_responses (
project text NOT NULL,
account_id uuid NOT NULL,
answers jsonb NOT NULL DEFAULT '{}' CHECK (jsonb_typeof(answers) = 'object'),
result jsonb NOT NULL DEFAULT '{}' CHECK (jsonb_typeof(result) = 'object'),
completed_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (project, account_id),
FOREIGN KEY (project, account_id) REFERENCES project_accounts ON DELETE CASCADE
);
CREATE TABLE workspaces (
project text NOT NULL,
id uuid NOT NULL DEFAULT gen_random_uuid(),
name text NOT NULL CHECK (length(trim(name)) BETWEEN 1 AND 160),
owner_id uuid NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (project, id),
FOREIGN KEY (project, owner_id) REFERENCES project_accounts
);
CREATE TABLE workspace_members (
project text NOT NULL,
workspace_id uuid NOT NULL,
account_id uuid NOT NULL,
role text NOT NULL CHECK (role IN ('admin', 'editor', 'viewer')),
joined_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (project, workspace_id, account_id),
FOREIGN KEY (project, workspace_id) REFERENCES workspaces ON DELETE CASCADE,
FOREIGN KEY (project, account_id) REFERENCES project_accounts ON DELETE CASCADE
);
CREATE INDEX workspace_members_account ON workspace_members(project, account_id);
CREATE TABLE materials (
project text NOT NULL,
workspace_id uuid NOT NULL,
id uuid NOT NULL DEFAULT gen_random_uuid(),
kind text NOT NULL CHECK (kind IN ('text', 'article', 'image', 'board', 'card')),
title text NOT NULL CHECK (length(title) <= 300),
description text NOT NULL DEFAULT '' CHECK (length(description) <= 10000),
content jsonb NOT NULL DEFAULT '{}' CHECK (jsonb_typeof(content) = 'object'),
version bigint NOT NULL DEFAULT 1 CHECK (version > 0),
created_by uuid NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
modified_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (project, workspace_id, id),
FOREIGN KEY (project, workspace_id) REFERENCES workspaces ON DELETE CASCADE,
FOREIGN KEY (project, created_by) REFERENCES project_accounts
);
CREATE INDEX material_modified ON materials(project, workspace_id, modified_at DESC, id);
CREATE INDEX material_created ON materials(project, workspace_id, created_at DESC, id);
CREATE INDEX material_alphabetical ON materials(project, workspace_id, lower(title), id);
CREATE TABLE material_opens (
project text NOT NULL,
workspace_id uuid NOT NULL,
material_id uuid NOT NULL,
account_id uuid NOT NULL,
opened_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (project, workspace_id, material_id, account_id),
FOREIGN KEY (project, workspace_id, material_id) REFERENCES materials ON DELETE CASCADE,
FOREIGN KEY (project, account_id) REFERENCES project_accounts ON DELETE CASCADE
);
CREATE INDEX material_opens_account ON material_opens(project, workspace_id, account_id, opened_at DESC);
CREATE TABLE tags (
project text NOT NULL,
workspace_id uuid NOT NULL,
id uuid NOT NULL DEFAULT gen_random_uuid(),
name text NOT NULL CHECK (length(trim(name)) BETWEEN 1 AND 80),
color text NOT NULL DEFAULT '',
PRIMARY KEY (project, workspace_id, id),
FOREIGN KEY (project, workspace_id) REFERENCES workspaces ON DELETE CASCADE
);
CREATE UNIQUE INDEX tag_name ON tags(project, workspace_id, lower(name));
CREATE TABLE material_tags (
project text NOT NULL,
workspace_id uuid NOT NULL,
material_id uuid NOT NULL,
tag_id uuid NOT NULL,
PRIMARY KEY (project, workspace_id, material_id, tag_id),
FOREIGN KEY (project, workspace_id, material_id) REFERENCES materials ON DELETE CASCADE,
FOREIGN KEY (project, workspace_id, tag_id) REFERENCES tags ON DELETE CASCADE
);
CREATE INDEX material_tags_filter ON material_tags(project, workspace_id, tag_id, material_id);
-- A board placement references a reusable material, independently of its content.
CREATE TABLE board_layouts (
project text NOT NULL,
workspace_id uuid NOT NULL,
board_id uuid NOT NULL,
id uuid NOT NULL DEFAULT gen_random_uuid(),
material_id uuid NOT NULL,
x double precision NOT NULL CHECK (x BETWEEN -1000000 AND 1000000),
y double precision NOT NULL CHECK (y BETWEEN -1000000 AND 1000000),
width double precision NOT NULL CHECK (width BETWEEN 1 AND 100000),
height double precision NOT NULL CHECK (height BETWEEN 1 AND 100000),
z_index integer NOT NULL DEFAULT 0,
version bigint NOT NULL DEFAULT 1 CHECK (version > 0),
PRIMARY KEY (project, workspace_id, board_id, id),
FOREIGN KEY (project, workspace_id, board_id) REFERENCES materials ON DELETE CASCADE,
FOREIGN KEY (project, workspace_id, material_id) REFERENCES materials ON DELETE CASCADE,
CHECK (board_id <> material_id)
);
CREATE TABLE material_grants (
project text NOT NULL,
workspace_id uuid NOT NULL,
material_id uuid NOT NULL,
account_id uuid NOT NULL,
role text NOT NULL CHECK (role IN ('editor', 'viewer')),
PRIMARY KEY (project, workspace_id, material_id, account_id),
FOREIGN KEY (project, workspace_id, material_id) REFERENCES materials ON DELETE CASCADE,
FOREIGN KEY (project, account_id) REFERENCES project_accounts ON DELETE CASCADE
);
CREATE TABLE share_links (
project text NOT NULL,
workspace_id uuid NOT NULL,
id uuid NOT NULL DEFAULT gen_random_uuid(),
material_id uuid,
token_hash text NOT NULL UNIQUE,
role text NOT NULL CHECK (role IN ('admin', 'editor', 'viewer')),
created_by uuid NOT NULL,
expires_at timestamptz NOT NULL,
revoked_at timestamptz,
max_uses integer CHECK (max_uses BETWEEN 1 AND 100000),
use_count integer NOT NULL DEFAULT 0 CHECK (use_count >= 0),
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (project, workspace_id, id),
FOREIGN KEY (project, workspace_id) REFERENCES workspaces ON DELETE CASCADE,
FOREIGN KEY (project, workspace_id, material_id) REFERENCES materials ON DELETE CASCADE,
FOREIGN KEY (project, created_by) REFERENCES project_accounts,
CHECK (material_id IS NULL OR role <> 'admin')
);
CREATE TABLE share_redemptions (
project text NOT NULL,
workspace_id uuid NOT NULL,
link_id uuid NOT NULL,
account_id uuid NOT NULL,
redeemed_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (project, workspace_id, link_id, account_id),
FOREIGN KEY (project, workspace_id, link_id) REFERENCES share_links ON DELETE CASCADE,
FOREIGN KEY (project, account_id) REFERENCES project_accounts ON DELETE CASCADE
);
CREATE TABLE link_clicks (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
project text NOT NULL,
workspace_id uuid NOT NULL,
link_id uuid NOT NULL,
clicked_at timestamptz NOT NULL DEFAULT now(),
-- Store the referring origin only, without URL paths, queries or user tokens.
referrer_origin text NOT NULL DEFAULT '',
FOREIGN KEY (project, workspace_id, link_id) REFERENCES share_links ON DELETE CASCADE
);
CREATE INDEX link_clicks_summary ON link_clicks(project, workspace_id, link_id, clicked_at);
COMMIT;
-29
View File
@@ -1,29 +0,0 @@
BEGIN;
ALTER TABLE materials ADD COLUMN canvas_version bigint NOT NULL DEFAULT 1 CHECK (canvas_version > 0);
ALTER TABLE materials ADD COLUMN canvas_document jsonb;
ALTER TABLE materials ADD CONSTRAINT canvas_board_only CHECK (canvas_document IS NULL OR kind='board');
ALTER TABLE workspaces ADD COLUMN slug text;
UPDATE workspaces SET slug=COALESCE(NULLIF(trim(both '-' from left(trim(both '-' from regexp_replace(lower(name),'[^a-z0-9]+','-','g')),50)),''),'workspace') || '-' || id::text;
ALTER TABLE workspaces ALTER COLUMN slug SET NOT NULL;
ALTER TABLE workspaces ADD CONSTRAINT workspace_slug_unique UNIQUE(project,slug);
ALTER TABLE workspaces ADD CONSTRAINT workspace_slug_valid CHECK (slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' AND length(slug)<=100);
ALTER TABLE materials ADD COLUMN slug text;
UPDATE materials SET slug=COALESCE(NULLIF(trim(both '-' from left(trim(both '-' from regexp_replace(lower(title),'[^a-z0-9]+','-','g')),50)),''),'canvas') || '-' || id::text;
ALTER TABLE materials ALTER COLUMN slug SET NOT NULL;
ALTER TABLE materials ADD CONSTRAINT material_slug_unique UNIQUE(project,workspace_id,slug);
ALTER TABLE materials ADD CONSTRAINT material_slug_valid CHECK (slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$' AND length(slug)<=100);
CREATE FUNCTION foundry_default_slug() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE label text;
BEGIN
IF NEW.slug IS NULL THEN
IF TG_TABLE_NAME='workspaces' THEN label=NEW.name; ELSE label=NEW.title; END IF;
label=left(trim(both '-' from regexp_replace(lower(label),'[^a-z0-9]+','-','g')),50);
NEW.slug=COALESCE(NULLIF(trim(both '-' from label),''),'canvas') || '-' || NEW.id::text;
END IF;
RETURN NEW;
END $$;
CREATE TRIGGER workspace_default_slug BEFORE INSERT ON workspaces FOR EACH ROW EXECUTE FUNCTION foundry_default_slug();
CREATE TRIGGER material_default_slug BEFORE INSERT ON materials FOR EACH ROW EXECUTE FUNCTION foundry_default_slug();
COMMIT;
-9
View File
@@ -1,9 +0,0 @@
BEGIN;
-- Existing sessions keep their current idle deadline: expired sessions stay expired.
-- Their original issuance time was not recorded, so the new absolute cap starts here.
ALTER TABLE project_sessions
ADD COLUMN created_at timestamptz NOT NULL DEFAULT now(),
ADD COLUMN absolute_expires_at timestamptz NOT NULL DEFAULT (now() + interval '90 days');
COMMIT;
-66
View File
@@ -1,66 +0,0 @@
BEGIN;
CREATE TABLE canvas_subgraphs (
project text NOT NULL,
workspace_id uuid NOT NULL,
parent_board_id uuid NOT NULL,
frame_id text NOT NULL CHECK (frame_id ~ '^[A-Za-z0-9_-]{1,128}$'),
child_board_id uuid NOT NULL,
archived_at timestamptz,
migration_source jsonb,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY(project,workspace_id,child_board_id),
FOREIGN KEY(project,workspace_id,parent_board_id) REFERENCES materials ON DELETE RESTRICT,
FOREIGN KEY(project,workspace_id,child_board_id) REFERENCES materials ON DELETE RESTRICT,
CHECK(parent_board_id<>child_board_id)
);
CREATE UNIQUE INDEX canvas_subgraph_active_frame ON canvas_subgraphs(project,workspace_id,parent_board_id,frame_id) WHERE archived_at IS NULL;
-- Workspace row locks serialize ownership changes. A database trigger also rejects
-- cycles and excessive depth for maintenance callers outside the HTTP service.
CREATE FUNCTION foundry_check_subgraph() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE depth integer;
BEGIN
PERFORM 1 FROM workspaces WHERE project=NEW.project AND id=NEW.workspace_id FOR UPDATE;
IF EXISTS(SELECT 1 FROM materials WHERE project=NEW.project AND workspace_id=NEW.workspace_id AND id IN(NEW.parent_board_id,NEW.child_board_id) AND kind<>'board') THEN
RAISE EXCEPTION 'subgraph requires boards' USING ERRCODE='23514';
END IF;
WITH RECURSIVE ancestors(id,path) AS (
SELECT NEW.parent_board_id,ARRAY[NEW.child_board_id,NEW.parent_board_id]
UNION ALL
SELECT s.parent_board_id,a.path||s.parent_board_id FROM ancestors a JOIN canvas_subgraphs s
ON s.project=NEW.project AND s.workspace_id=NEW.workspace_id AND s.child_board_id=a.id
WHERE NOT s.parent_board_id=ANY(a.path) AND s.archived_at IS NULL
) SELECT max(cardinality(path)-1) INTO depth FROM ancestors;
IF depth>8 OR EXISTS(WITH RECURSIVE descendants(id,path) AS (
SELECT NEW.child_board_id,ARRAY[NEW.child_board_id]
UNION ALL SELECT s.child_board_id,d.path||s.child_board_id FROM descendants d JOIN canvas_subgraphs s
ON s.project=NEW.project AND s.workspace_id=NEW.workspace_id AND s.parent_board_id=d.id
WHERE NOT s.child_board_id=ANY(d.path) AND s.archived_at IS NULL
) SELECT 1 FROM descendants WHERE id=NEW.parent_board_id OR cardinality(path)+depth-1>8) THEN
RAISE EXCEPTION 'subgraph cycle or depth exceeded' USING ERRCODE='23514';
END IF;
RETURN NEW;
END $$;
CREATE TRIGGER canvas_subgraph_integrity BEFORE INSERT OR UPDATE ON canvas_subgraphs FOR EACH ROW EXECUTE FUNCTION foundry_check_subgraph();
CREATE TABLE canvas_transactions (
project text NOT NULL,
workspace_id uuid NOT NULL,
board_id uuid NOT NULL,
id uuid NOT NULL DEFAULT gen_random_uuid(),
account_id uuid NOT NULL,
action text NOT NULL,
idempotency_key uuid NOT NULL,
payload_hash text NOT NULL,
response_status integer NOT NULL,
response_body jsonb NOT NULL,
before_state jsonb NOT NULL,
after_versions jsonb NOT NULL,
relation_changes jsonb NOT NULL DEFAULT '[]'::jsonb,
created_at timestamptz NOT NULL DEFAULT now(),
expires_at timestamptz NOT NULL DEFAULT now()+interval '7 days',
undone_at timestamptz,
PRIMARY KEY(project,workspace_id,id),
UNIQUE(project,workspace_id,account_id,board_id,action,idempotency_key),
FOREIGN KEY(project,workspace_id,board_id) REFERENCES materials ON DELETE RESTRICT,
FOREIGN KEY(project,account_id) REFERENCES project_accounts
);
COMMIT;
-32
View File
@@ -1,32 +0,0 @@
BEGIN;
-- Keeping the encoded object in PostgreSQL makes object creation, bindings and
-- idempotency atomic. A future blob backend can replace bytes without changing
-- stable application URLs or canvas references.
CREATE TABLE canvas_assets (
project text NOT NULL,
workspace_id uuid NOT NULL,
id uuid NOT NULL DEFAULT gen_random_uuid(),
uploaded_by uuid NOT NULL,
mime_type text NOT NULL CHECK(mime_type IN('image/png','image/jpeg','image/gif','image/webp')),
bytes bytea NOT NULL CHECK(octet_length(bytes) BETWEEN 1 AND 20971520),
width integer NOT NULL CHECK(width>0),
height integer NOT NULL CHECK(height>0),
digest text NOT NULL,
idempotency_key uuid NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY(project,workspace_id,id),
UNIQUE(project,workspace_id,uploaded_by,idempotency_key),
FOREIGN KEY(project,workspace_id) REFERENCES workspaces ON DELETE CASCADE,
FOREIGN KEY(project,uploaded_by) REFERENCES project_accounts
);
CREATE TABLE canvas_asset_bindings (
project text NOT NULL,
workspace_id uuid NOT NULL,
asset_id uuid NOT NULL,
board_id uuid NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY(project,workspace_id,asset_id,board_id),
FOREIGN KEY(project,workspace_id,asset_id) REFERENCES canvas_assets ON DELETE RESTRICT,
FOREIGN KEY(project,workspace_id,board_id) REFERENCES materials ON DELETE CASCADE
);
COMMIT;
-80
View File
@@ -1,80 +0,0 @@
BEGIN;
CREATE TABLE canvas_ai_runs (
project text NOT NULL,
workspace_id uuid NOT NULL,
board_id uuid NOT NULL,
id uuid NOT NULL DEFAULT gen_random_uuid(),
account_id uuid NOT NULL,
idempotency_key uuid NOT NULL,
payload_hash text NOT NULL,
status text NOT NULL CHECK(status IN('queued','running','succeeded','partially_succeeded','failed','cancelled','conflict')),
plan jsonb NOT NULL,
create_response jsonb NOT NULL,
error_code text,
cancel_requested boolean NOT NULL DEFAULT false,
lease_id uuid,
lease_until timestamptz,
last_seq bigint NOT NULL DEFAULT 0 CHECK(last_seq>=0),
available_at timestamptz NOT NULL DEFAULT now(),
created_at timestamptz NOT NULL DEFAULT now(),
completed_at timestamptz,
expires_at timestamptz NOT NULL DEFAULT now()+interval '30 days',
PRIMARY KEY(project,workspace_id,id),
UNIQUE(project,workspace_id,account_id,board_id,idempotency_key),
FOREIGN KEY(project,workspace_id,board_id) REFERENCES materials ON DELETE RESTRICT,
FOREIGN KEY(project,account_id) REFERENCES project_accounts
);
CREATE INDEX canvas_ai_pending ON canvas_ai_runs(available_at,created_at,id) WHERE status='queued';
CREATE INDEX canvas_ai_active ON canvas_ai_runs(project,workspace_id,board_id,created_at,id) WHERE status IN('queued','running');
CREATE TABLE canvas_ai_steps (
project text NOT NULL,
workspace_id uuid NOT NULL,
run_id uuid NOT NULL,
id text NOT NULL,
board_id uuid NOT NULL,
node_id text NOT NULL,
ordinal integer NOT NULL CHECK(ordinal>=0),
status text NOT NULL CHECK(status IN('queued','running','succeeded','failed','cancelled','conflict','skipped')),
model_id text NOT NULL,
frozen_input jsonb NOT NULL,
target_fingerprint text NOT NULL,
output jsonb,
error_code text,
applied_version bigint,
started_at timestamptz,
completed_at timestamptz,
PRIMARY KEY(project,workspace_id,run_id,id),
UNIQUE(project,workspace_id,run_id,board_id,node_id),
FOREIGN KEY(project,workspace_id,run_id) REFERENCES canvas_ai_runs ON DELETE CASCADE,
FOREIGN KEY(project,workspace_id,board_id) REFERENCES materials ON DELETE RESTRICT
);
CREATE UNIQUE INDEX canvas_ai_node_busy ON canvas_ai_steps(project,workspace_id,board_id,node_id) WHERE status IN('queued','running');
CREATE TABLE canvas_ai_events (
project text NOT NULL,
workspace_id uuid NOT NULL,
run_id uuid NOT NULL,
seq bigint NOT NULL CHECK(seq>0),
type text NOT NULL,
data jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY(project,workspace_id,run_id,seq),
FOREIGN KEY(project,workspace_id,run_id) REFERENCES canvas_ai_runs ON DELETE CASCADE
);
-- Per-run serialization increments last_seq and inserts an event in one statement.
-- A lease which expires after a worker started is not automatically re-executed:
-- recovery marks the uncertain step failed, preventing duplicate model invocations.
CREATE TABLE canvas_ai_mutations (
project text NOT NULL,
workspace_id uuid NOT NULL,
run_id uuid NOT NULL,
account_id uuid NOT NULL,
action text NOT NULL,
idempotency_key uuid NOT NULL,
payload_hash text NOT NULL,
response_body jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY(project,workspace_id,run_id,account_id,action,idempotency_key),
FOREIGN KEY(project,workspace_id,run_id) REFERENCES canvas_ai_runs ON DELETE CASCADE,
FOREIGN KEY(project,account_id) REFERENCES project_accounts
);
COMMIT;
-103
View File
@@ -1,103 +0,0 @@
BEGIN;
-- Canonical rows are separate from the legacy snapshot. Adoption is an explicit,
-- version-checked transaction; installing this schema does not migrate user data.
CREATE TABLE canvas_model_projects (
project text NOT NULL,
workspace_id uuid NOT NULL,
root_id uuid NOT NULL,
document_format_version integer NOT NULL DEFAULT 1 CHECK(document_format_version=1),
migration_id uuid NOT NULL,
source_versions jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY(project,workspace_id,root_id),
FOREIGN KEY(project,workspace_id,root_id) REFERENCES materials ON DELETE CASCADE
);
CREATE TABLE canvas_model_canvases (
project text NOT NULL,
workspace_id uuid NOT NULL,
root_id uuid NOT NULL,
canvas_id uuid NOT NULL,
parent_canvas_id uuid,
entry_element_id text,
version bigint NOT NULL CHECK(version>0),
archived boolean NOT NULL DEFAULT false,
PRIMARY KEY(project,workspace_id,canvas_id),
UNIQUE(project,canvas_id),
UNIQUE(project,workspace_id,root_id,canvas_id),
CHECK((parent_canvas_id IS NULL)=(entry_element_id IS NULL)),
CHECK(parent_canvas_id IS NOT NULL OR canvas_id=root_id),
FOREIGN KEY(project,workspace_id,root_id) REFERENCES canvas_model_projects ON DELETE CASCADE,
FOREIGN KEY(project,workspace_id,canvas_id) REFERENCES materials ON DELETE CASCADE,
FOREIGN KEY(project,workspace_id,root_id,parent_canvas_id) REFERENCES canvas_model_canvases(project,workspace_id,root_id,canvas_id) DEFERRABLE INITIALLY DEFERRED
);
CREATE UNIQUE INDEX canvas_model_active_entry ON canvas_model_canvases(project,workspace_id,entry_element_id) WHERE NOT archived;
CREATE TABLE canvas_model_elements (
project text NOT NULL,
workspace_id uuid NOT NULL,
root_id uuid NOT NULL,
element_id text NOT NULL CHECK(element_id ~ '^[A-Za-z0-9_-]{1,128}$'),
owner_canvas_id uuid NOT NULL,
incarnation bigint NOT NULL CHECK(incarnation>0 AND incarnation<=9007199254740991),
deleted_incarnation bigint NOT NULL DEFAULT 0 CHECK(deleted_incarnation>=0 AND deleted_incarnation<=incarnation),
record jsonb NOT NULL,
deleted boolean NOT NULL DEFAULT false,
PRIMARY KEY(project,element_id),
UNIQUE(project,workspace_id,element_id),
CHECK(jsonb_typeof(record)='object' AND record->>'id'=element_id AND record->>'ownerCanvasId'=owner_canvas_id::text AND (record->>'incarnation')::bigint=incarnation),
CHECK(NOT deleted OR deleted_incarnation=incarnation),
FOREIGN KEY(project,workspace_id,root_id) REFERENCES canvas_model_projects ON DELETE CASCADE,
FOREIGN KEY(project,workspace_id,root_id,owner_canvas_id) REFERENCES canvas_model_canvases(project,workspace_id,root_id,canvas_id) DEFERRABLE INITIALLY DEFERRED
);
CREATE INDEX canvas_model_owner ON canvas_model_elements(project,workspace_id,root_id,owner_canvas_id) WHERE NOT deleted;
ALTER TABLE canvas_model_canvases ADD CONSTRAINT canvas_model_entry_fk FOREIGN KEY(project,workspace_id,entry_element_id) REFERENCES canvas_model_elements(project,workspace_id,element_id) DEFERRABLE INITIALLY DEFERRED;
CREATE TABLE canvas_model_identity_map (
project text NOT NULL,
workspace_id uuid NOT NULL,
root_id uuid NOT NULL,
source_canvas_id uuid NOT NULL,
source_structure text NOT NULL CHECK(source_structure IN('node','connection')),
source_element_id text NOT NULL,
element_id text NOT NULL,
PRIMARY KEY(project,workspace_id,root_id,source_canvas_id,source_structure,source_element_id),
UNIQUE(project,element_id),
FOREIGN KEY(project,workspace_id,root_id) REFERENCES canvas_model_projects ON DELETE CASCADE,
FOREIGN KEY(project,workspace_id,element_id) REFERENCES canvas_model_elements(project,workspace_id,element_id) DEFERRABLE INITIALLY DEFERRED
);
-- Logical operations cannot acquire a second successful execution under a new request key.
CREATE TABLE canvas_model_requests (
project text NOT NULL,
workspace_id uuid NOT NULL,
account_id uuid NOT NULL,
request_id uuid NOT NULL,
root_id uuid NOT NULL,
action text NOT NULL,
protocol_version integer NOT NULL,
payload_hash text NOT NULL,
response_status integer NOT NULL,
response_body jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY(project,workspace_id,account_id,request_id),
FOREIGN KEY(project,workspace_id,root_id) REFERENCES materials ON DELETE RESTRICT,
FOREIGN KEY(project,account_id) REFERENCES project_accounts
);
CREATE TABLE canvas_model_operations (
project text NOT NULL,
workspace_id uuid NOT NULL,
operation_id uuid NOT NULL,
request_id uuid NOT NULL,
account_id uuid NOT NULL,
PRIMARY KEY(project,workspace_id,operation_id),
FOREIGN KEY(project,workspace_id,account_id,request_id) REFERENCES canvas_model_requests DEFERRABLE INITIALLY DEFERRED,
FOREIGN KEY(project,account_id) REFERENCES project_accounts
);
CREATE FUNCTION foundry_guard_canonical_canvas() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF (NEW.canvas_document IS DISTINCT FROM OLD.canvas_document OR NEW.canvas_version IS DISTINCT FROM OLD.canvas_version)
AND EXISTS(SELECT 1 FROM canvas_model_canvases c WHERE c.project=NEW.project AND c.workspace_id=NEW.workspace_id AND c.canvas_id=NEW.id)
AND current_setting('foundry.canonical_writer',true) IS DISTINCT FROM 'on' THEN
RAISE EXCEPTION 'canonical_write_required' USING ERRCODE='55000';
END IF;
RETURN NEW;
END $$;
CREATE TRIGGER canonical_canvas_write_barrier BEFORE UPDATE OF canvas_document,canvas_version ON materials FOR EACH ROW EXECUTE FUNCTION foundry_guard_canonical_canvas();
COMMIT;
-6
View File
@@ -1,6 +0,0 @@
BEGIN;
-- Legacy requests retain NULL. Canonical operation identity cannot be replayed
-- under another transport key to admit a second paid execution.
ALTER TABLE canvas_ai_runs ADD COLUMN logical_operation_id uuid;
CREATE UNIQUE INDEX canvas_ai_logical_operation ON canvas_ai_runs(project,workspace_id,account_id,logical_operation_id) WHERE logical_operation_id IS NOT NULL;
COMMIT;
-29
View File
@@ -1,29 +0,0 @@
BEGIN;
-- Keep transport receipts independently from execution retention. Their absence
-- must never be used as proof that a paid invocation did not happen.
CREATE TABLE canvas_ai_requests (
project text NOT NULL,
workspace_id uuid NOT NULL,
account_id uuid NOT NULL,
request_id uuid NOT NULL,
board_id uuid NOT NULL,
run_id uuid,
action text NOT NULL CHECK(action IN('run.start','run.cancel','run.apply')),
operation_id uuid NOT NULL,
payload_hash text NOT NULL,
outcome text NOT NULL CHECK(outcome IN('applied','not-applied')),
response_status integer NOT NULL,
response_body jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY(project,workspace_id,account_id,request_id),
FOREIGN KEY(project,workspace_id) REFERENCES workspaces(project,id) ON DELETE CASCADE
);
-- A known zero-effect rejection may be explicitly replanned under another key;
-- a completed logical action must never execute twice under different keys.
CREATE UNIQUE INDEX canvas_ai_request_operation ON canvas_ai_requests(project,workspace_id,account_id,operation_id) WHERE outcome='applied';
-- Preserve accepted canonical requests that predate this receipt table.
INSERT INTO canvas_ai_requests(project,workspace_id,account_id,request_id,board_id,action,operation_id,payload_hash,outcome,response_status,response_body)
SELECT project,workspace_id,account_id,idempotency_key,board_id,'run.start',logical_operation_id,payload_hash,'applied',202,create_response
FROM canvas_ai_runs WHERE logical_operation_id IS NOT NULL AND create_response->>'protocol_version'='2'
ORDER BY created_at,id ON CONFLICT DO NOTHING;
COMMIT;
-9
View File
@@ -1,9 +0,0 @@
BEGIN;
-- The frozen board remains the plan origin; result versions belong to the board
-- that actually received the output after any owner-only move.
ALTER TABLE canvas_ai_steps ADD COLUMN applied_board_id uuid;
ALTER TABLE canvas_ai_steps ADD FOREIGN KEY(project,workspace_id,applied_board_id) REFERENCES materials(project,workspace_id,id);
UPDATE canvas_ai_steps SET applied_board_id=board_id WHERE applied_version IS NOT NULL;
CREATE UNIQUE INDEX canvas_ai_canonical_target_busy ON canvas_ai_steps(project,workspace_id,(frozen_input->>'canonical_root'),node_id,(frozen_input->>'target_incarnation'))
WHERE status IN('queued','running') AND frozen_input->>'canonical_root' IS NOT NULL;
COMMIT;
+79
View File
@@ -0,0 +1,79 @@
# Deployment configuration
Bedrock reads a YAML deployment file from `BEDROCK_DB_CONFIG`. The loader also accepts TOML and existing JSON files.
| Deployment method | Directory |
|---|---|
| Local SQLite | [local/](local/) |
| Gitea release to the existing host | [gitea/](gitea/) |
| Kubernetes | [kubernetes/](kubernetes/) |
## Local SQLite
Run `backend --init-storage` to initialize storage once. Bedrock defaults to `bedrock.sqlite3` in the working directory. To choose another path, set `BEDROCK_DB_CONFIG` to a [SQLite configuration](local/sqlite.yaml) and set the resource's `primary` to a persistent, writable path.
```mermaid
flowchart TD
A["在本机运行 backend --init-storage"] --> B{"是否设置 BEDROCK_DB_CONFIG"}
B -->|是| C["读取指定的 SQLite 配置,取得文件路径"]
B -->|否| D["使用工作目录下的 bedrock.sqlite3"]
C --> E["打开或创建 SQLite 文件"]
D --> E
E --> F["Bedrock 初始化文档存储"]
```
## Gitea release to the existing host
PostgreSQL on the existing host uses Gitea Actions variables `BEDROCK_PG_HOST`, `BEDROCK_PG_PORT`, `BEDROCK_PG_DATABASE`, `BEDROCK_PG_USER` and secret `BEDROCK_PG_PASSWORD`. The release invokes `python3 deploy/gitea/render-postgres.py /path/to/private/bedrock.yaml --deployment production --config-version RELEASE_ID`. The renderer writes a private file. The database must already exist and present a trusted certificate for the selected endpoint.
Gitea builds a release on `ces-control` when a commit lands on `main`. The deploy step renders the private PostgreSQL configuration and runs `backend --init-storage` through the published `bedrock` executable on the existing `endoleap-dev_default` network. It publishes releases under `/opt/endoleap-infra/bedrock-rust/releases` and switches `/opt/endoleap-infra/bedrock-rust/current` after successful initialization. The Go service retains its own containers and routes.
```mermaid
flowchart TD
M["main 收到提交"] --> W["deploy.yml 在 ces-control 上启动"]
W --> B["build-release.sh 编译 backend 发布版"]
B -->|Bedrock 二进制和 Git SHA| R
E["Gitea PostgreSQL Variables 和 Secret"] -->|部署参数| P
subgraph release["release.sh"]
R["暂存待发布版本"] --> P["调用 render-postgres.py 生成私有 bedrock.yaml"]
P -->|配置就绪| I["临时容器运行 backend 的 --init-storage,初始化 PostgreSQL"]
I -->|成功| S["保存版本并原子切换 current"]
P -->|失败| F["清理暂存目录,保留现有 current"]
I -->|失败| F
end
```
## Kubernetes
The database and Bedrock workload manifests are supplied by the deployment. Use each database's Service DNS name as its address, such as `pg-main:5432` within the same namespace. The [multi-storage example](kubernetes/multi-storage.yaml) shows how to declare resource kinds, drivers and role bindings. Render the final YAML with deployment credentials, store it in a Secret, and mount it into the Bedrock workload at the path set in `BEDROCK_DB_CONFIG`. The optional [catalog ConfigMap](kubernetes/kubernetes-catalog.yaml) packages named resources for the library import API.
```mermaid
flowchart TD
A["准备 Kubernetes 工作负载和数据库 Service"] --> B["用 Service 名称配置数据库连接地址"]
B --> C["用 multi-storage.yaml 的结构准备 Bedrock 配置和用途绑定"]
D["可选:从 ConfigMap 导入命名资源"] -.-> C
E["部署时提供数据库凭据"] --> C
C --> F["把私有 bedrock.yaml 写入 Kubernetes Secret"]
F --> G["Bedrock Pod 挂载配置,设置 BEDROCK_DB_CONFIG"]
G --> H["Bedrock 通过 Service 地址连接数据库"]
```
## Shared deployment settings
Terraform or cloud inventory can export the chosen endpoints. Map those results into the Bedrock resource schema before importing. `ImportFormat::TerraformOutputs` reads a named `bedrock_resources` output from `terraform output -json`. Generic catalogs use names as keys and the same `kind` fields shown in the Kubernetes example. Role bindings are assigned in the deployment configuration under `bindings`.
Publish the same versioned configuration to every instance in a deployment. Use a new configuration version and restart instances to apply changes. Rollouts can temporarily contain two versions. The catalog APIs edit an in-process draft. Publish the validated YAML through the deployment system to apply it across instances.
S3 entries describe endpoints and buckets. Keep access credentials in the deployment's secret store for the eventual object storage client.
Pull requests currently run without an automatic storage check. The optional `ci/check-sql.sh` script uses isolated database containers and generated fixture credentials when run on an approved remote runner.
## Manual SQL checks
```mermaid
flowchart TD
H["在远程 runner 手动运行"] --> C["ci/check-sql.sh 创建临时网络和数据库容器"]
C --> T["测试 SQLite、PostgreSQL 和 MySQL"]
T -->|退出时| U["清理测试容器和临时网络"]
```
-53
View File
@@ -1,53 +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
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}"
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"
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
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。
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/foundry,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/foundry 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
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
-102
View File
@@ -1,102 +0,0 @@
#!/usr/bin/env bash
# 远程 runner 的数据库/集成检查,会编译测试二进制并运行容器;不能在未授权本地环境执行。
set -euo pipefail
# 随机隔离数据库容器不映射宿主端口,EXIT 时销毁;trust 认证只用于该临时网络命名空间。
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
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
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
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'
psql < internal/research/testdata/corpus.sql
# runner 编译 Linux 静态测试程序,随后在同数据库网络空间用最小权限容器运行,源码不挂入测试容器。
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 客户端集成;未提供时跳过该阶段。
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
-33
View File
@@ -1,33 +0,0 @@
#!/usr/bin/env bash
# 远程私有 worker 启动器;使用与 Core 同一二进制的 codex-worker 模式,CLI 和登录目录由运维预先提供。
set -euo pipefail
base=/opt/endoleap-infra
dir=$base/foundry/codex
binary=$(realpath "$1")
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,不共享本登录目录。
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/foundry,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/foundry codex-worker
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env bash
set -euo pipefail
output="$PWD/target/bedrock-release"
mkdir -p "$output"
docker run --rm \
--mount "type=bind,source=$PWD,target=/work,readonly" \
--mount "type=bind,source=$output,target=/out" \
-w /work -e CARGO_TARGET_DIR=/tmp/bedrock-target \
rust:1.91.1-bookworm sh -ec '
cargo build --locked --release -p backend
install -m 755 /tmp/bedrock-target/release/backend /out/bedrock
'
+50
View File
@@ -0,0 +1,50 @@
#!/usr/bin/env bash
set -euo pipefail
umask 077
binary=${1:?Path to the built Bedrock executable is required}
revision=${2:?Git commit is required}
if [[ ! $revision =~ ^[0-9a-f]{40}$ || ! -x $binary ]]; then
printf 'Invalid release commit or executable\n' >&2
exit 1
fi
infra=/opt/endoleap-infra
root=$infra/bedrock-rust
network=endoleap-dev_default
test -d "$infra"
test ! -L "$root"
docker network inspect "$network" >/dev/null
install -d -m 700 "$root/releases"
stage=$(mktemp -d "$root/releases/.staging.XXXXXXXX")
cleanup() { rm -rf -- "$stage"; }
trap cleanup EXIT
install -m 755 "$binary" "$stage/bedrock"
release="$revision.${stage##*.}"
python3 "$(dirname "$0")/render-postgres.py" "$stage/bedrock.yaml" \
--deployment production --config-version "$release"
# Run storage initialization as a one-shot command in the release container.
docker run --rm --network "$network" \
--user "$(id -u):$(id -g)" --read-only --cap-drop ALL --security-opt no-new-privileges \
--mount "type=bind,source=$stage,target=/release,readonly" \
-e BEDROCK_DB_CONFIG=/release/bedrock.yaml \
debian:bookworm-slim /release/bedrock --init-storage
# Keep the final release private; only switch current after initialization succeeds.
python3 - "$stage" "$root" "$release" <<'PY'
import os
from pathlib import Path
import sys
import tempfile
stage, root, release = Path(sys.argv[1]), Path(sys.argv[2]), sys.argv[3]
destination = Path("releases") / release
stage.rename(root / destination)
with tempfile.TemporaryDirectory(prefix=".activate.", dir=root) as activation:
link = Path(activation) / "current"
link.symlink_to(destination)
os.replace(link, root / "current")
PY
printf 'Published Bedrock Rust release %s\n' "$release"
+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/env python3
"""Render the private Bedrock PostgreSQL config at deploy time."""
import argparse
import ipaddress
import json
import os
from pathlib import Path
import re
import tempfile
from urllib.parse import quote
def required(variable):
value = os.environ.get(variable)
if not value:
raise SystemExit(f"Missing {variable}")
return value
def database_url():
host = required("BEDROCK_PG_HOST").removeprefix("[").removesuffix("]")
if ":" in host:
try:
host = f"[{ipaddress.IPv6Address(host)}]"
except ValueError:
raise SystemExit("Invalid BEDROCK_PG_HOST") from None
elif not re.fullmatch(r"[A-Za-z0-9.-]+", host):
raise SystemExit("Invalid BEDROCK_PG_HOST")
try:
port = int(required("BEDROCK_PG_PORT"))
if not 1 <= port <= 65535:
raise ValueError
except ValueError:
raise SystemExit("Invalid BEDROCK_PG_PORT") from None
user = quote(required("BEDROCK_PG_USER"), safe="")
password = quote(required("BEDROCK_PG_PASSWORD"), safe="")
database = quote(required("BEDROCK_PG_DATABASE"), safe="")
return f"postgres://{user}:{password}@{host}:{port}/{database}"
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("output", type=Path)
parser.add_argument("--deployment", default="default")
parser.add_argument("--config-version", default="local")
options = parser.parse_args()
if not re.fullmatch(r"[A-Za-z0-9._-]{1,128}", options.deployment):
parser.error("invalid deployment name")
if not re.fullmatch(r"[A-Za-z0-9._-]{1,128}", options.config_version):
parser.error("invalid config version")
# JSON quoting is valid for scalars in YAML and handles special characters.
config = (
f"deployment: {json.dumps(options.deployment)}\n"
f"config_version: {json.dumps(options.config_version)}\n"
"bindings:\n"
" documents: postgres\n"
"resources:\n"
" postgres:\n"
" kind: sql\n"
" driver: postgres\n"
f" primary: {json.dumps(database_url())}\n"
)
# Write with owner-only permissions, then replace the destination atomically.
file = tempfile.NamedTemporaryFile(mode="w", dir=options.output.parent, delete=False)
try:
with file:
file.write(config)
os.replace(file.name, options.output)
finally:
Path(file.name).unlink(missing_ok=True)
if __name__ == "__main__":
main()
+16
View File
@@ -0,0 +1,16 @@
# Resource catalog for ImportFormat::KubernetesConfigMap.
apiVersion: v1
kind: ConfigMap
metadata:
name: bedrock-resources
data:
bedrock-resources.yaml: |
pg-main:
kind: sql
driver: postgres
primary: postgres://bedrock@pg-main:5432/bedrock
attachments:
kind: object_store
driver: s3
bucket: bedrock-attachments
region: us-east-1
+21
View File
@@ -0,0 +1,21 @@
# Illustrative service names. Inject deployment credentials before publishing.
deployment: production
config_version: example-1
resources:
pg-main:
kind: sql
driver: postgres
primary: postgres://bedrock@pg-main:5432/bedrock
mysql-legacy:
kind: sql
driver: mysql
primary: mysql://bedrock@mysql-legacy:3306/legacy
attachment-store:
kind: object_store
driver: s3
bucket: bedrock-attachments
region: us-east-1
bindings:
documents: pg-main
legacy: mysql-legacy
attachments: attachment-store
+10
View File
@@ -0,0 +1,10 @@
deployment: default
config_version: local
resources:
local:
kind: sql
driver: sqlite
primary: bedrock.sqlite3
max_connections: 1
bindings:
documents: local
-85
View File
@@ -1,85 +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")
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 = 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",
])
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")
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 命令参数。
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.")
-188
View File
@@ -1,188 +0,0 @@
#!/usr/bin/env bash
# 由 main 部署工作流在远程基础设施主机执行,参数一必须是已构建的 Foundry 二进制。
# 本脚本会迁移数据库、替换 worker 并启动候选服务,不能当作本地静态检查执行。
set -euo pipefail
umask 077
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
)
export FOUNDRY_PROJECTS
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/foundry"
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
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_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
worker_ready=false
if bash "$(dirname "$0")/codex-worker.sh" "$release/foundry" >/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"
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
# 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/foundry,target=/opt/foundry,readonly" \
node:24-bookworm-slim /opt/foundry >/dev/null
# 候选或路由失败时删除本次新 Core;旧 Core 由 route 成功探测后才停止。
cleanup_candidate() {
docker rm -f "${live:-$candidate}" >/dev/null 2>&1 || true
}
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 update --restart unless-stopped "$live" >/dev/null
bash "$(dirname "$0")/route.sh" "$live"
trap - EXIT
printf 'Foundry readiness and unauthenticated rejection verified.\n'
-18
View File
@@ -1,18 +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.
SET lock_timeout = '2s';
SET statement_timeout = '20min';
SET maintenance_work_mem = '32MB';
SET max_parallel_maintenance_workers = 0;
-- (tag_id,paper_id) 支持纯主题页直接走关联索引,在 LIMIT 前避免读所有宽论文行。
CREATE INDEX CONCURRENTLY IF NOT EXISTS paper_tags_tag_paper
ON research.paper_tags(tag_id,paper_id);
-- simple 配置匹配作者查询的表达式,不对姓名做 english 词干化;索引表达式须与查询一致。
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.
-87
View File
@@ -1,87 +0,0 @@
#!/usr/bin/env bash
# 远程部署的路由切换阶段,参数必须是本次已通过内部就绪检查的 Core 容器名。
set -euo pipefail
umask 077
cd /opt/endoleap-infra
live=$1
[[ "$live" =~ ^foundry-core-[a-f0-9]{12}$ ]]
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
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"
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 配置,不重建其他服务。
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
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
-115
View File
@@ -1,115 +0,0 @@
-- Foundry 数据库源码阅读注释索引(仅注释,不执行迁移)。
-- 历史 db/*.sql 的 SHA-256 由 deploy/migrate.py 原文计算并记录;即使只改注释,
-- 已部署库也会拒绝同名文件的新校验和。因此按迁移文件与对象名在此维护中文说明。
-- 顺序:001 认证 → 002 平台 → 003 快照 → 004 会话期限 → 005 子图事务 →
-- 006 资产 → 007 AI 队列 → 008 canonical 模型 → 009–011 AI 身份/回执/位置。
-- db/001-auth.sql:四张基础认证表在一个事务中安装。
-- project_accounts:账户身份以 (project,id) 为主键,Google subject 在项目内唯一。
-- 同一 Google 用户可在不同项目有不同账户,邮箱是可空资料,不作为跨提供方自动合并依据。
-- oauth_attempts:十分钟 OAuth 尝试;state/browser 保存摘要,frontend_challenge 绑定
-- 前端兑换证明,google_verifier 原文用于服务器向 Google 兑换 PKCE 授权码。
-- 回调通过 DELETE ... RETURNING 原子消费,外部兑换失败也不会恢复已消费尝试。
-- login_grants:一分钟一次性交换码只存 token_hash,复合外键保证账户属于同一项目。
-- project_sessions:bearer 明文只交客户端,数据库仅存摘要和期限;删除账户级联清会话。
-- 三个 expires_at 索引提供过期定位能力,本文件本身不创建定时清理任务。
-- db/002-platform.sql:扩展身份提供方与协作资源,保留旧 Google 账户/会话。
-- project_accounts:google_subject 放宽可空;username 在项目内按 lower 唯一,
-- display_name/avatar_url 是可由用户维护的资料,updated_at 由应用更新。
-- oauth_attempts.provider 默认 google 兼容已有行;Slack 增加 oidc_nonce 防止 ID token 重放。
-- account_identities:以项目/提供方/subject 唯一定位账户,迁入既有 Google subject;
-- 项目/提供方/account 唯一约束限定同一账户每提供方只有一个绑定。
-- email_credentials:已验证邮箱凭据,邮箱须小写,password_hash 是 bcrypt;
-- 项目/email 主键及项目/account 唯一性不允许多个凭据冒用同一邮箱或账户。
-- email_registrations:未验证注册单独保存密码摘要和验证码摘要,未确认前不建立账户;
-- 重发注册由应用在邮箱级事务锁下替换待验证记录及过期时间。
-- email_outbox:邮件与注册同事务写入,available_at/attempts 控制重试;lease_id/
-- lease_until 使后台 worker 可认领并在租约失效后恢复,sent_at 标成功。
-- 发送成功后应用清空 body;SMTP 成功与数据库标记不原子,不能宣称严格只投递一次。
-- auth_rate_limits:仅保存限频键摘要,固定窗口过期后由应用 upsert 重置次数。
-- onboarding_responses:项目/账户唯一完成记录,answers/result 必须 JSON 对象;
-- 配合账户行锁,使并发首次引导只能创建一次工作区并重放已存结果。
-- workspaces:所有者外键指向同项目账户;工作区行锁是角色/所有权变更共享的串行点。
-- workspace_members:每人每工作区一个角色,admin/editor/viewer 的写权限由应用解释;
-- owner 必须保留 admin 成员的规则由服务控制,表约束没有单独自动生成该成员。
-- materials:按项目/工作区隔离的可复用内容对象,kind 为受限类型;version 是素材
-- 内容/元数据的乐观版本,后续新增 canvas_version 与它分离。
-- material_modified/material_created/material_alphabetical:对应列表排序的复合索引。
-- material_opens:账户级最近打开时间,可反复 upsert,不修改素材正文;专用索引支持最近打开。
-- tags/material_tags:标签名在工作区内忽略大小写唯一;双复合外键阻止跨工作区关联,
-- 标签/素材删除级联清关联,应用负责让受影响素材版本递增。
-- board_layouts:旧布局引用可复用素材,位置/尺寸与内容独立;禁止引用自身,
-- “必须 board 且不可嵌套 board”及每板最多 2000 条由服务检查。
-- material_grants:显式 editor/viewer 素材权限,不存在素材级 admin 授予;
-- 根画布继承和归档祖先检查由 lockMaterial 的递归查询决定。
-- share_links:仅保存邀请摘要;可指工作区或单素材,单素材不允许 admin;
-- max_uses/use_count 是额度,expires_at/revoked_at 控制之后的兑换资格。
-- share_redemptions:同账户同链接只兑换一次;应用在持锁事务内插入成功后才加额度并提升角色。
-- link_clicks:公开点击独立于兑换计数,仅存 Referer origin,避免收集路径、查询和令牌。
-- bigint identity 支持递减 ID 分页;应用角色需单独授予序列 USAGE/SELECT。
-- db/003-canvas.sql:为 board 增加独立 canvas_version 和可空 canvas_document。
-- canvas_board_only 禁止非 board 保存快照;旧空文档在读取时投影为初始空 v1 图。
-- workspaces/materials 的 slug 先按名称/标题加 UUID 回填,再设 NOT NULL 和作用域唯一。
-- foundry_default_slug:仅 INSERT 且未给 slug 才派生值,名字更改不会隐式改 URL。
-- label 规范化并限长,空结果回退 canvas;触发器在两个表共享,因此区分 name/title。
-- db/004-session-lifetime.sql:加入 created_at 和九十天 absolute_expires_at 缺省。
-- 旧会话原始发行时间未知,绝对上限从迁移时开始,但原 expires_at 完全不变,
-- 已闲置过期的旧会话不会被此迁移复活。应用续期取 min(三十天后,绝对期限)。
-- db/005-canvas-subgraphs.sql:持久唯一所有权与多画布事务恢复信息。
-- canvas_subgraphs:Child 是主键中的唯一所有者身份,活跃 Parent/Frame 受部分唯一索引限制;
-- archived_at 保留恢复关系但从活跃树移除;migration_source 保存旧框迁移证据。
-- 父/子外键均 RESTRICT,不能删掉素材而留下无法解释的所有权记录。
-- foundry_check_subgraph:先锁工作区,确认两端是 board,再递归算祖先和后代,
-- 拒绝循环与深度超八;数据库触发器也保护绕过 HTTP 的维护写入。
-- canvas_transactions:账户/画布/动作/幂等键唯一,payload_hash 防止同键换体。
-- response_status/body 冻结重放结果;before_state、after_versions、relation_changes
-- 支持条件撤销;expires_at 七天及 undone_at 控制撤销有效性,不会自动倒退当前版本。
-- db/006-canvas-assets.sql:编码原图 bytea 与绑定同库事务提交,URL 与存储后端解耦。
-- canvas_assets:限制格式和二十 MiB 编码预算,上传者/工作区/幂等键唯一,digest 为原图摘要;
-- 完整像素预算与解码有效性由应用在写入前检查,不能只依赖 MIME 字符串。
-- canvas_asset_bindings:资产可被多个画布引用,主键去重;删除画布级联清绑定,
-- 有绑定资产不能直接删除。可读性按当前绑定画布授权判断,缓存字节不能作为权限证明。
-- db/007-canvas-ai.sql:run/step/event 与旧取消/显式应用回执。
-- canvas_ai_runs:冻结 plan/create_response,保存队列时间、取消位、租约与单调 last_seq;
-- pending 部分索引服务认领,active 索引服务活跃列表;expires_at 表示三十天保留期限。
-- canvas_ai_steps:每 run 的拓扑 ordinal、冻结输入、目标指纹、输出与应用版本;
-- 局部 board/node 活跃部分唯一索引防止同目标同时重复生成。
-- canvas_ai_events:以 run/seq 主键保证重放顺序;appendAIEvent 用同一 SQL 推进 last_seq。
-- canvas_ai_mutations:旧协议按 run/账户/动作/键冻结应用和取消结果;不同于 run 生成重试。
-- 租约过期不证明模型尚未执行,恢复把未知执行标为中断,只有明确 codex_busy 才允许回队。
-- db/008-canvas-model.sql:只安装 canonical schema,不自动迁移已有用户快照。
-- canvas_model_projects:每根显式迁移身份屏障,记录源版本表与 migration_id。
-- canvas_model_canvases:树关系、入口元素、独立版本及 archived;父/入口同时可空,
-- 无父只能是根;延迟外键允许入口元素与孩子关系在同批创建,提交时再验证。
-- canvas_model_active_entry 部分唯一索引防止一个活跃入口拥有多个子画布。
-- canvas_model_elements:主键 (project,element_id) 使身份跨工作区/树不可被抢占;
-- record 的 id/owner/incarnation 必须与索引列相符,删除记录保留 deleted_incarnation。
-- owner 外键延迟验证,支持同事务移动所有权;应用验证整个最终树和连接共同祖先。
-- canvas_model_identity_map:保留来源画布/结构/旧 ID 到稳定元素 ID 的完整一次性映射。
-- canvas_model_requests:账户作用域请求键、动作、摘要、状态与冻结回执,确定拒绝也可恢复。
-- canvas_model_operations:逻辑 ID 独立于传输 request_id 去重,外键延迟到同事务回执落库;
-- 只有应用成功才消费逻辑身份,拒绝前缀不能把其中操作标为已执行。
-- foundry_guard_canonical_canvas:已迁入树的 canvas_document/version 改写需事务内
-- foundry.canonical_writer=on,阻止旧写入路径覆盖权威身份。此标志是应用协作约定,不替代数据库角色权限。
-- db/009-canvas-ai-operations.sql:为 run 增加可空 logical_operation_id,旧行保持 NULL。
-- 部分唯一索引限定项目/工作区/账户下同逻辑操作只能准入一个 run,换传输键不能重复付费执行。
-- db/010-canvas-ai-receipts.sql:把传输回执从执行保留周期中分离。
-- canvas_ai_requests:允许 run.start/cancel/apply,保存 applied/not-applied 与原始请求身份;
-- 不以 run 外键级联删除,使 run 清理后仍可判定已知结果,工作区删除则整体清理。
-- applied 逻辑操作部分唯一:确定零效果拒绝可显式用新键重计划,已应用操作不能再次执行。
-- INSERT ... SELECT 从旧 canonical run 回填 accepted 回执,ON CONFLICT 保留已有记录。
-- 回执缺失只能回答 unknown,不能证明历史付费调用从未发生。
-- db/011-canvas-ai-target-location.sql:分离冻结来源与实际应用位置。
-- applied_board_id:结果写到 owner 移动后的目标画布,旧已应用行按原 board_id 回填。
-- canvas_ai_canonical_target_busy:按根/稳定节点/代数而非原 board 唯一限制活跃步骤,
-- owner-only 移动不能逃过 node_busy,再次删除/恢复的新代则由生命周期检查单独处理。
-196
View File
@@ -1,196 +0,0 @@
# Shared research API
This work belongs to Thesisly 研迹 and uses Foundry Core rather than a separate
application backend. The corpus is public; account sessions and future private
collections remain project scoped.
## Current implementation boundary
`internal/research` implements the HTTP contract and a PostgreSQL repository
based on the fixed Paper Atlas `a3b677b` schema (TEXT/BIGINT columns, native
English title/abstract search index). `cmd/foundry` enables it only when
`FOUNDRY_RESEARCH_DATABASE_URL` is configured. The Paper Atlas migration is now published: 21 tables passed its independent
count/content-hash acceptance. A dedicated `foundry_research_reader` role has
SELECT on the ten tables consumed here, schema USAGE, and read-only defaults.
Its connection is stored only in the protected server file below.
The existing SQLite implementation was withdrawn. Real-corpus integration has
been checked through a loopback Core and the local frontend. Formal production
release still requires the user to merge and choose to deploy; this branch is
not deployed by these checks. Very broad queries remain subject to the budget
and performance limitation documented below.
Do not add `FOUNDRY_RESEARCH_DATABASE`.
The server-side deployment may load a protected
`/opt/endoleap-infra/foundry/research.env` containing
`FOUNDRY_RESEARCH_DATABASE_URL` and `FOUNDRY_RESEARCH_SCHEMA` (default `research`).
Keep the connection string out of Git, Actions variables, browser configuration
and command arguments. Use a dedicated role with schema USAGE and table SELECT
only. Core uses a separate two-connection pool, read-only connection defaults and
read-only transactions. Each research transaction disables JIT locally: the
measured count plan spent about 2.85 seconds compiling JIT functions, and its
end-to-end execution exceeded eight seconds. This does not alter shared
PostgreSQL settings or replace exact counts with estimates. Startup checks the published schema/SELECT permissions;
an explicitly enabled but invalid connection fails candidate readiness.
Deployment migration defaults now follow the shared `foundry-postgres`
container name. `FOUNDRY_POSTGRES_CONTAINER` or the existing `--container` option
can select a different container without changing database/table names.
## Routes
- `GET /projects/{project}/research/papers`
- `GET /projects/{project}/research/papers/{id}`
Only configured Foundry projects are accepted. Reading the public corpus does
not require a session; these routes do not expose private data or accept writes.
List parameters are `q` (200 Unicode characters, 20 words), `searchIn`
(`text` or `author`), `topic` (an exact arXiv category), `sort` (`recent` or
`title`), `cursor` (optional, opaque, at most 32768 characters), and
`pageSize` (1–50, default 8). Unknown, malformed
or repeated parameters return 400. `recent` means descending stable paper ID,
not publication date. Search terms must become bound query parameters, never
raw SQL or user-supplied full-text syntax.
Title/abstract search uses the migration's English vector with
`plainto_tsquery`; author search uses simple-language terms over the stored
author JSON. Both treat input as terms, never full-text operators. Initial full-corpus measurements showed eight-second timeouts for text,
author and topic counts; the unfiltered count took 7.25 seconds. Execution plans
confirmed sequential scans for authors and category joins.
`deploy/research/query-indexes.sql` supplies operator-run concurrent indexes for
those two missing access paths. It is separate from Core startup and auth
migrations; do not grant DDL to the runtime reader. Both indexes completed on the confirmed ECS (category 35.4 seconds, author
436.47 seconds); measured end-to-end checks are documented below.
List responses contain `items`, `nextCursor`, `previousCursor`, `topics`, and
`pageSize`. Empty cursor strings mean that direction is unavailable. There is
no `total`, page number, total page count or deep-page cap. The old `page`
parameter is rejected; coordinate the frontend/backend contract update.
Each paper preserves original title/abstract, authors, source dates, topics and
source links. Publication decisions need source evidence; absent decisions stay
unknown. No invented repositories, metrics or generated research conclusions.
Lists use a read-only repeatable-read snapshot without `count(*)` or `OFFSET`.
Keyset paging uses ID descending for recent order and `(title_key, id)` ascending
for title order, including a reverse query for previous pages. The title key is
kept in its stored codec and C collation. Cursors bind normalized query, search
scope, topic, sort and page size; changing filters requires a fresh cursor. They
are public row positions, not authorization tokens or guaranteed frozen snapshots
across requests. Concurrent corpus edits may alter later pages.
Only pageSize+1 positions are selected; the extra position indicates more data,
then full rows and batched metadata are loaded for at most pageSize papers.
For recent order with only a topic filter, page directly through the existing
`(tag_id,paper_id)` index and deduplicate evidence before LIMIT. For text/author
search in recent order, try an ID interval of 512 near the cursor, expanding
once to 4096 only if there are some matches but fewer than pageSize+1.
Only a full page plus one proves that interval contains the next page. If neither bounded attempt fills the page,
all local candidates are discarded and the complete indexed search is used;
rare or older matches are never silently truncated. The fallback materializes
matching IDs before sorting, avoiding an unbounded ordered heap scan for sparse
terms. Title-order filtered queries still use that complete search and can time
out for broad terms. No global database or proxy resource settings are changed.
The
HTTP layer permits two in-flight queries with an eight-second context budget.
Busy requests return 429 with `Retry-After: 1`; deadlines return 504; storage
errors return a generic 503 without database details. Missing papers return 404.
## Validation
`go test -race -count=1 ./internal/research` covers routing, query limits,
Unicode, anonymous reads, rejected mutations, project lookup, errors, saturation
and timeout slot release. Run compilation/tests only on the user-confirmed ECS
runner. These transport tests do not prove a database connection, full-corpus
query performance or production availability.
The PostgreSQL repository batches source/tag/identifier/submission queries in
the same read-only repeatable-read transaction. Author tuples are displayed as
given name, family name and suffix; an optional fourth affiliation field
is excluded from the display name (observed in real arXiv records); null abstracts/dates remain null. Publication
status comes from the latest observed decision, using decision date and ID as
tie-breakers, and stays unknown when no decision exists. Unit checks cover
author shapes, bound user values and schema qualification. The real Core detail
and homepage HTTP routes have returned 200.
The frontend has also rendered the actual 3,526,999-paper corpus through a
loopback SSH tunnel: eight rows, matching detail title/source, desktop and
mobile layout, no page exceptions or horizontal overflow in that check.
The earlier count-based API returned 146 author records in 0.336 seconds. Before the cursor optimization, after paging/author fixes, category `cs.AR` returned 9,457 records in 4.906
seconds, `CartoonGAN` returned three in 0.332 seconds, and the multi-term search
`attention is all you need` returned 8,653 in 6.325 seconds. These were sequential
manual HTTP checks, not a load test. Very broad text searches can still exceed
the eight-second budget; clients retain search controls so users can narrow
the query or retry. This known limit is not an estimated count or sample
fallback. This is not a
production deployment or an authentication acceptance result.
The existing `deploy/check-schema.sh` also loads the synthetic fixture in
`internal/research/testdata/corpus.sql` inside its disposable PostgreSQL
container (`--network none`, no host port). The research test process receives a
separate SELECT-only fixture role via `RESEARCH_TEST_DATABASE_URL`. These
integration checks execute real SQL for filtering, stable paging, nullable
content, source/tag/identifier joins, latest decision tie-breakers, permission
denial and SQL-backed HTTP routes. They never connect to the shared migration
instance and do not establish full-corpus performance or live-data correctness.
## Text storage compatibility (repair 4e62710)
The Paper Atlas repair uses `nul-soh-v1`: NUL is stored as SOH/SOH, and a
literal SOH as SOH/STX, preserving binary text ordering. Core reads the schema
comment `paper-atlas:text-codec=nul-soh-v1` through `pg_catalog` at startup,
restores SQL text before JSON parsing/API responses, and encodes bound search
terms. An absent/unrelated schema comment keeps legacy text unchanged; an
unsupported marked codec or malformed encoded text fails explicitly.
Schema comments are public metadata, so consumers need no privileges on the
private migration controller. The research role still needs only schema USAGE
and table SELECT. The codec adaptation is on the review branch, pushed with [skip ci] under the
user's no-CI instruction; the published schema marker has been verified with
the runtime reader.
All research tests passed manually against disposable PostgreSQL on the
confirmed ECS, including the encoded SQL fixture for schema detection, raw TEXT restoration,
JSON author/metadata decoding, search and the HTTP round trip. Passing isolated
fixtures does not establish full-corpus API performance.
## Identity handoff
The existing production Core received a configuration-only reload using its
unchanged release binary: the original projects were retained and thesisly was
registered. Both Google and Slack identity records were observed in this
project. The user independently confirmed each provider's real authorization,
reload/new-tab persistence and logout behavior. Browser control was unavailable,
so these browser results are attributed to user acceptance rather than an
automated real-account test. This does not deploy the research work branch;
mail delivery was not exercised.
## Cursor regression coverage
The disposable PostgreSQL fixture covers forward/backward traversal, identical
title keys with different IDs, published control-character encoding, sparse
matches separated by a large ID gap, and fallback from the bounded interval.
Invalid, oversized, cross-filter and wrong-version cursors are rejected before
repository execution. The runtime reader retains SELECT-only privileges; no DDL
or writes are added. Run tests manually on the confirmed ECS; skip CI for this
iteration and retain `[skip ci]` in commit and PR titles.
## Manual cursor measurements (2026-11-07)
On the confirmed ECS, after this task's compilation and disposable fixture had
finished, sequential direct requests to the temporary Core returned: homepage
65 ms, next/previous 39/21 ms, `graph` 345 ms, `CartoonGAN` 731 ms (3 papers),
`cs.AR` 145 ms, title order 180 ms, author `Buhrman` 769 ms, and
`attention is all you need` 1312 ms. Recent, topic and title cursor round trips
returned the same first page without overlap. These are individual manual
samples, not production latency guarantees; concurrent compilation earlier
produced multi-second cold measurements. No proxy, database memory, CPU or
production configuration was changed.
The final source compiled manually on the ECS; package unit checks and all ten
selected cursor/PostgreSQL integration tests passed, including interval expansion
and complete fallback. No CI or local build ran. The local authorized Next dev
uses the temporary API through the existing SSH tunnel. Independent Chrome also
verified real homepage/search navigation, a preserved document, one mobile
header/main, no page exceptions and no horizontal overflow. The production Core
was not replaced by these temporary preview updates.
-21
View File
@@ -1,21 +0,0 @@
// Foundry Go 模块身份,internal 包的导入前缀必须与此一致。
module gitea.entroia.com/Zayden-Jung/foundry-core
// CI 从此读取工具链版本,避免开发和远程构建使用不同语言契约。
go 1.25.0
// 直接依赖提供 PostgreSQL 驱动/事务与图片解码缩放能力。
require (
github.com/jackc/pgx/v5 v5.7.6
golang.org/x/image v0.25.0
)
// 以下保留 Go 模块图要求的间接依赖;版本校验摘要由 go.sum 管理。
require (
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/puddle/v2 v2.2.2 // indirect
golang.org/x/crypto v0.37.0 // indirect
golang.org/x/sync v0.13.0 // indirect
golang.org/x/text v0.24.0 // indirect
)
-30
View File
@@ -1,30 +0,0 @@
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
github.com/jackc/pgx/v5 v5.7.6 h1:rWQc5FwZSPX58r1OQmkuaNicxdmExaEz5A2DO2hUuTk=
github.com/jackc/pgx/v5 v5.7.6/go.mod h1:aruU7o91Tc2q2cFp5h4uP3f6ztExVpyVv88Xl/8Vl8M=
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE=
golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc=
golang.org/x/image v0.25.0 h1:Y6uW6rH1y5y/LK1J8BPWZtr6yZ7hrsy6hFrXjgsc2fQ=
golang.org/x/image v0.25.0/go.mod h1:tCAmOEGthTtkalusGp1g3xa2gke8J6c2N565dTyl9Rs=
golang.org/x/sync v0.13.0 h1:AauUjRAJ9OSnvULf/ARrrVywoJDy0YS2AwQ98I37610=
golang.org/x/sync v0.13.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=
golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
-362
View File
@@ -1,362 +0,0 @@
// Package auth 管理项目隔离的登录:提供方回调产生 grant,前端凭 verifier 换取 bearer 会话。
package auth
import (
"context"
"crypto/rand"
"crypto/sha256"
"database/sql"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"golang.org/x/crypto/bcrypt"
"io"
"log"
"net/http"
"net/url"
"regexp"
"strings"
"time"
)
// 项目名限制为可用于路由的短标识;令牌格式对应 32 随机字节的无填充 base64url。
var projectName = regexp.MustCompile(`^[a-z][a-z0-9-]*$`)
var tokenPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{43}$`)
// service 共享数据库、回调白名单和外部 HTTP 客户端;passwordSlots 限制 bcrypt 并发。
type service struct {
db *sql.DB
projects map[string]*url.URL
redirectURI, clientID, secret string
google *http.Client
email *EmailConfig
passwordSlots chan struct{}
dummyPassword []byte
slack *SlackConfig
}
// New 由进程入口调用,验证项目回调并返回独立认证路由;db 的关闭由调用方负责。
func New(db *sql.DB, callbacks map[string]string, redirectURI, id, secret string, email *EmailConfig, slack *SlackConfig) (http.Handler, error) {
// 未注册邮箱也执行同成本密码比对,减少通过响应耗时区分账号存在性的差异。
dummy, err := bcrypt.GenerateFromPassword([]byte("foundry-invalid-login-placeholder"), bcrypt.DefaultCost)
if err != nil {
return nil, err
}
s := &service{db: db, email: email, slack: slack, passwordSlots: make(chan struct{}, 4), dummyPassword: dummy, projects: make(map[string]*url.URL), redirectURI: redirectURI, clientID: id, secret: secret,
google: &http.Client{Timeout: 10 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}
// 回调固定在配置白名单,生产要求 HTTPS,开发仅允许回环主机使用 HTTP。
for name, raw := range callbacks {
u, err := url.Parse(raw)
if err != nil {
return nil, fmt.Errorf("invalid project callback for %q", name)
}
host := u.Hostname()
local := u.Scheme == "http" && (host == "localhost" || host == "127.0.0.1" || host == "::1")
if !projectName.MatchString(name) || host == "" || (u.Scheme != "https" && !local) || u.User != nil || u.Fragment != "" {
return nil, fmt.Errorf("invalid project callback for %q", name)
}
s.projects[name] = u
}
// healthz 仅说明进程可响应;readyz 查询账户表,覆盖连接与基础 schema 就绪性。
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { reply(w, 200, payload{"status": "ok"}) })
mux.HandleFunc("GET /readyz", s.wrap(func(w http.ResponseWriter, r *http.Request) error {
if _, err := s.db.ExecContext(r.Context(), "SELECT 1 FROM project_accounts LIMIT 1"); err != nil {
return err
}
reply(w, 200, payload{"status": "ready"})
return nil
}))
mux.HandleFunc("/auth/slack/callback", s.wrap(s.slackCallback))
mux.HandleFunc("GET /auth/google/callback", s.wrap(s.callback))
mux.HandleFunc("/projects/{project}/auth/{action}", s.wrap(s.project))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("Referrer-Policy", "no-referrer")
ctx, cancel := context.WithTimeout(r.Context(), 25*time.Second)
defer cancel()
mux.ServeHTTP(w, r.WithContext(ctx))
}), nil
}
// payload 是小型 JSON 响应对象,nil 响应体用于 204 等无内容结果。
type payload map[string]any
// reply 必须在尚未写响应时调用;编码/网络错误当前由调用链忽略。
func reply(w http.ResponseWriter, status int, body payload) {
if body != nil {
w.Header().Set("Content-Type", "application/json")
}
w.WriteHeader(status)
if body != nil {
_ = json.NewEncoder(w).Encode(body)
}
}
// reject 已写出预期业务错误并返回 nil,避免 wrap 再次将它改写为 503。
func reject(w http.ResponseWriter, status int, code string) error {
reply(w, status, payload{"error": code})
return nil
}
// wrap 将未处理依赖错误统一返回 503,日志仅记录类型,避免泄露凭据和提供方响应。
func (s *service) wrap(handle func(http.ResponseWriter, *http.Request) error) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := handle(w, r); err != nil {
log.Printf("request failed (%T)", err)
_ = reject(w, 503, "service_unavailable")
}
}
}
// token 生成可放入 Cookie、URL fragment 或请求头的随机凭据。
func token() string {
var value [32]byte
rand.Read(value[:])
return base64.RawURLEncoding.EncodeToString(value[:])
}
// digest 用于凭据落库摘要和 S256 challenge;不用于密码存储,密码使用 bcrypt。
func digest(value string) string {
sum := sha256.Sum256([]byte(value))
return base64.RawURLEncoding.EncodeToString(sum[:])
}
// project 先校验项目,再分派登录与会话动作;Origin 缺省的服务端请求仍可进入认证。
func (s *service) project(w http.ResponseWriter, r *http.Request) error {
project, action := r.PathValue("project"), r.PathValue("action")
frontend := s.projects[project]
if frontend == nil {
return reject(w, 404, "not_found")
}
if r.Method == http.MethodGet && action == "slack" {
return s.startSlack(w, r, project)
}
if r.Method == http.MethodGet && action == "google" {
return s.start(w, r, project)
}
w.Header().Set("Vary", "Origin")
if origin := r.Header.Get("Origin"); origin != "" {
if origin != frontend.Scheme+"://"+frontend.Host {
return reject(w, 403, "origin_denied")
}
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Expose-Headers", SessionExpiryHeader)
}
switch {
case r.Method == http.MethodOptions:
w.Header().Set("Access-Control-Allow-Methods", "GET, POST")
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Foundry-Code, X-Foundry-Verifier")
reply(w, 204, nil)
case r.Method == http.MethodPost && (action == "register" || action == "verify-email" || action == "login"):
return s.emailAction(w, r, project, action)
case r.Method == http.MethodPost && action == "exchange":
return s.exchange(w, r, project)
case r.Method == http.MethodGet && action == "me":
return s.account(w, r, project, false)
case r.Method == http.MethodPost && action == "logout":
return s.account(w, r, project, true)
default:
return reject(w, 405, "method_not_allowed")
}
return nil
}
// oauthCookie 以随机 state 区分并行登录,__Host- 前缀配合 Secure、根路径和无 Domain。
func oauthCookie(state, value string, maxAge int) *http.Cookie {
return &http.Cookie{Name: "__Host-foundry-oauth-" + state, Value: value, Path: "/", MaxAge: maxAge,
Secure: true, HttpOnly: true, SameSite: http.SameSiteLaxMode}
}
// start 保存十分钟 OAuth 尝试;browser 绑定浏览器,verifier 用于 Google 端 PKCE。
// 前端 challenge 是另一层兑换证明,最终与 login_grants 绑定。
func (s *service) start(w http.ResponseWriter, r *http.Request, project string) error {
challenge := r.URL.Query().Get("challenge")
if !tokenPattern.MatchString(challenge) {
return reject(w, 400, "invalid_challenge")
}
state, browser, verifier := token(), token(), token()
_, err := s.db.ExecContext(r.Context(), `
INSERT INTO oauth_attempts(state_hash,browser_hash,project,frontend_challenge,google_verifier,expires_at) VALUES ($1, $2, $3, $4, $5, now() + interval '10 minutes')
`, digest(state), digest(browser), project, challenge, verifier)
if err != nil {
return err
}
query := url.Values{
"client_id": {s.clientID}, "redirect_uri": {s.redirectURI}, "response_type": {"code"},
"scope": {"openid email profile"}, "state": {state}, "code_challenge": {digest(verifier)},
"code_challenge_method": {"S256"}, "prompt": {"select_account"},
}
http.SetCookie(w, oauthCookie(state, browser, 600))
http.Redirect(w, r, "https://accounts.google.com/o/oauth2/v2/auth?"+query.Encode(), 302)
return nil
}
// googleJSON 同时用于 Google 和 Slack;客户端拒绝重定向,响应解码最多读取 1 MiB。
func (s *service) googleJSON(ctx context.Context, method, endpoint string, form url.Values, bearer string, result any) error {
var body io.Reader
if form != nil {
body = strings.NewReader(form.Encode())
}
req, err := http.NewRequestWithContext(ctx, method, endpoint, body)
if err != nil {
return err
}
if form != nil {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
if bearer != "" {
req.Header.Set("Authorization", "Bearer "+bearer)
}
res, err := s.google.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != 200 {
return fmt.Errorf("Google returned HTTP %d", res.StatusCode)
}
return json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(result)
}
// callback 原子删除 OAuth 尝试后换取 Google 身份;后续网络失败也不能重放该 state。
func (s *service) callback(w http.ResponseWriter, r *http.Request) error {
ctx := r.Context()
query := r.URL.Query()
state := query.Get("state")
if !tokenPattern.MatchString(state) {
return reject(w, 400, "invalid_state")
}
browser, err := r.Cookie(oauthCookie(state, "", 0).Name)
if err != nil || !tokenPattern.MatchString(browser.Value) {
return reject(w, 400, "invalid_state")
}
var project, challenge, verifier string
err = s.db.QueryRowContext(ctx, `
DELETE FROM oauth_attempts
WHERE state_hash = $1 AND browser_hash = $2 AND expires_at > now() AND provider='google'
RETURNING project, frontend_challenge, google_verifier
`, digest(state), digest(browser.Value)).Scan(&project, &challenge, &verifier)
if errors.Is(err, sql.ErrNoRows) {
return reject(w, 400, "invalid_state")
}
if err != nil {
return err
}
frontend := s.projects[project]
if frontend == nil {
return reject(w, 400, "invalid_state")
}
http.SetCookie(w, oauthCookie(state, "", -1))
// 复制共享 URL 后再写 fragment,避免并发请求改动项目白名单;交换码不放查询参数。
destination := *frontend
code := query.Get("code")
if code == "" || query.Has("error") {
destination.Fragment = "error=google_login_cancelled"
http.Redirect(w, r, destination.String(), 302)
return nil
}
var tokens struct {
AccessToken string `json:"access_token"`
}
err = s.googleJSON(ctx, "POST", "https://oauth2.googleapis.com/token", url.Values{
"code": {code}, "client_id": {s.clientID}, "client_secret": {s.secret}, "redirect_uri": {s.redirectURI},
"grant_type": {"authorization_code"}, "code_verifier": {verifier},
}, "", &tokens)
if err != nil {
return err
}
if tokens.AccessToken == "" {
return errors.New("missing Google access token")
}
var user struct {
Subject string `json:"sub"`
Email *string `json:"email"`
Verified bool `json:"email_verified"`
Name string `json:"name"`
Picture string `json:"picture"`
}
if err := s.googleJSON(ctx, "GET", "https://openidconnect.googleapis.com/v1/userinfo", nil, tokens.AccessToken, &user); err != nil {
return err
}
if user.Subject == "" {
return errors.New("missing Google subject")
}
if !user.Verified {
user.Email = nil
}
grant, err := s.identityGrant(ctx, project, "google", user.Subject, user.Email, user.Name, user.Picture, challenge)
if err != nil {
return err
}
destination.Fragment = "code=" + grant
http.Redirect(w, r, destination.String(), 302)
return nil
}
// exchange 在同一 SQL 中消费一次性 grant 并建会话;项目、challenge、期限必须全部匹配。
func (s *service) exchange(w http.ResponseWriter, r *http.Request, project string) error {
code, verifier := r.Header.Get("X-Foundry-Code"), r.Header.Get("X-Foundry-Verifier")
if !tokenPattern.MatchString(code) || !tokenPattern.MatchString(verifier) {
return reject(w, 400, "invalid_exchange")
}
session := token()
result, err := s.db.ExecContext(r.Context(), `
WITH redeemed_grant AS (
DELETE FROM login_grants
WHERE token_hash = $1 AND project = $2 AND frontend_challenge = $3 AND expires_at > now()
RETURNING account_id
)
INSERT INTO project_sessions(token_hash,project,account_id,expires_at)
SELECT $4, $2, account_id, now() + interval '30 days' FROM redeemed_grant
`, digest(code), project, digest(verifier), digest(session))
if err != nil {
return err
}
count, err := result.RowsAffected()
if err != nil {
return err
}
if count == 0 {
return reject(w, 401, "invalid_grant")
}
reply(w, 200, payload{"access_token": session, "token_type": "Bearer", "expires_in": SessionIdleSeconds})
return nil
}
// account 的 me 分支校验并续期,logout 按项目删除摘要且允许重复注销返回 204。
func (s *service) account(w http.ResponseWriter, r *http.Request, project string, logout bool) error {
token, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
if !ok || !tokenPattern.MatchString(token) {
return reject(w, 401, "invalid_session")
}
if logout {
_, err := s.db.ExecContext(r.Context(), "DELETE FROM project_sessions WHERE token_hash = $1 AND project = $2", digest(token), project)
if err != nil {
return err
}
reply(w, 204, nil)
return nil
}
session, err := AuthenticateSession(r.Context(), s.db, project, r.Header.Get("Authorization"))
if errors.Is(err, ErrInvalidSession) {
return reject(w, 401, "invalid_session")
}
if err != nil {
return err
}
var email *string
err = s.db.QueryRowContext(r.Context(), "SELECT email FROM project_accounts WHERE project=$1 AND id=$2", project, session.AccountID).Scan(&email)
if err != nil {
return err
}
WriteSessionHeaders(w, session)
id := session.AccountID
reply(w, 200, payload{"project": project, "id": id, "email": email})
return nil
}
-229
View File
@@ -1,229 +0,0 @@
// 邮箱登录链路:注册写待验证记录和 outbox,确认链接才创建账户;登录直接校验 bcrypt。
package auth
import (
"context"
"database/sql"
"encoding/json"
"errors"
"io"
"net/http"
"net/mail"
"strings"
"golang.org/x/crypto/bcrypt"
)
// emailAddress 统一大小写并拒绝显示名形式,只接受最多 254 字节的纯邮箱地址。
func emailAddress(value string) (string, bool) {
value = strings.ToLower(strings.TrimSpace(value))
address, err := mail.ParseAddress(value)
return value, err == nil && address.Address == value && len(value) <= 254
}
// emailBody 限制 16 KiB、拒绝未知字段及尾随 JSON;失败时已经写出 400。
func emailBody(w http.ResponseWriter, r *http.Request, input any) bool {
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16384))
decoder.DisallowUnknownFields()
if decoder.Decode(input) != nil || decoder.Decode(new(any)) != io.EOF {
_ = reject(w, 400, "invalid_request")
return false
}
return true
}
// rateLimit 将键摘要计入数据库十五分钟固定窗口,过期后第一次访问重新计数。
func (s *service) rateLimit(ctx context.Context, key string, limit int) (bool, error) {
var count int
err := s.db.QueryRowContext(ctx, `
INSERT INTO auth_rate_limits(key_hash,attempts,expires_at) VALUES($1,1,now()+interval '15 minutes')
ON CONFLICT(key_hash) DO UPDATE SET
attempts=CASE WHEN auth_rate_limits.expires_at<=now() THEN 1 ELSE auth_rate_limits.attempts+1 END,
expires_at=CASE WHEN auth_rate_limits.expires_at<=now() THEN now()+interval '15 minutes' ELSE auth_rate_limits.expires_at END
RETURNING attempts
`, digest(key)).Scan(&count)
return count <= limit, err
}
// emailAction 由 project 路由调用;先限频,再以非阻塞信号量限制密码哈希占用。
func (s *service) emailAction(w http.ResponseWriter, r *http.Request, project, action string) error {
if action == "verify-email" {
return s.verifyEmail(w, r, project)
}
var input struct {
Email string `json:"email"`
Password string `json:"password"`
}
if !emailBody(w, r, &input) {
return nil
}
email, valid := emailAddress(input.Email)
if !valid || len(input.Password) < 12 || len(input.Password) > 72 {
return reject(w, 400, "invalid_credentials_format")
}
limit := 10
if action == "register" {
if s.email == nil {
return reject(w, 503, "email_not_configured")
}
limit = 3
}
allowed, err := s.rateLimit(r.Context(), action+":"+project+":"+email, limit)
if err != nil {
return err
}
if !allowed {
w.Header().Set("Retry-After", "900")
return reject(w, 429, "rate_limited")
}
// 四个槽位都忙时立即返回 429,不让昂贵 bcrypt 请求无限排队。
select {
case s.passwordSlots <- struct{}{}:
defer func() { <-s.passwordSlots }()
default:
w.Header().Set("Retry-After", "2")
return reject(w, 429, "auth_busy")
}
if action == "register" {
return s.registerEmail(w, r, project, email, input.Password)
}
var account, hash string
err = s.db.QueryRowContext(r.Context(), "SELECT account_id::text,password_hash FROM email_credentials WHERE project=$1 AND email=$2", project, email).Scan(&account, &hash)
missing := errors.Is(err, sql.ErrNoRows)
if err != nil && !missing {
return err
}
passwordHash := []byte(hash)
// 不存在的账户使用启动时生成的 dummy 哈希,但无论密码比对结果如何均拒绝登录。
if missing {
passwordHash = s.dummyPassword
}
if bcrypt.CompareHashAndPassword(passwordHash, []byte(input.Password)) != nil || missing {
return reject(w, 401, "invalid_credentials")
}
session := token()
_, err = s.db.ExecContext(r.Context(), "INSERT INTO project_sessions(token_hash,project,account_id,expires_at) VALUES($1,$2,$3,now()+interval '30 days')", digest(session), project, account)
if err != nil {
return err
}
reply(w, 200, payload{"access_token": session, "token_type": "Bearer", "expires_in": SessionIdleSeconds})
return nil
}
// registerEmail 在邮箱级事务锁下更新三十分钟验证记录,邮件与记录共同提交。
// 已注册邮箱不写新邮件,仍返回相同 202,避免从此响应枚举账号。
func (s *service) registerEmail(w http.ResponseWriter, r *http.Request, project, email, password string) error {
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return err
}
tx, err := s.db.BeginTx(r.Context(), nil)
if err != nil {
return err
}
defer tx.Rollback()
if _, err = tx.ExecContext(r.Context(), "SELECT pg_advisory_xact_lock(hashtextextended($1,0))", "email:"+project+":"+email); err != nil {
return err
}
verification := token()
result, err := tx.ExecContext(r.Context(), `
INSERT INTO email_registrations(project,email,password_hash,token_hash,expires_at)
SELECT $1,$2,$3,$4,now()+interval '30 minutes'
WHERE NOT EXISTS(SELECT 1 FROM email_credentials WHERE project=$1 AND email=$2)
ON CONFLICT(project,email) DO UPDATE SET password_hash=EXCLUDED.password_hash,token_hash=EXCLUDED.token_hash,expires_at=EXCLUDED.expires_at
`, project, email, string(hash), digest(verification))
if err != nil {
return err
}
n, err := result.RowsAffected()
if err != nil {
return err
}
if n > 0 {
destination := *s.projects[project]
destination.Fragment = "verify_email=" + verification
body := "Confirm your email address for " + project + ".\r\n\r\n" + destination.String() + "\r\n\r\nThis link expires in 30 minutes. If you did not register, ignore this email."
_, err = tx.ExecContext(r.Context(), `
INSERT INTO email_outbox(project,recipient,subject,body,expires_at) VALUES($1,$2,'Verify your email', $3, now()+interval '30 minutes')
`, project, email, body)
if err != nil {
return err
}
}
if err = tx.Commit(); err != nil {
return err
}
reply(w, 202, payload{"status": "verification_requested"})
return nil
}
// verifyEmail 先定位邮箱再加同一事务锁,随后删除并返回有效记录以保证验证码一次性消费。
// 账户、邮箱凭据、会话都成功后才提交,任何失败交由 defer 回滚。
func (s *service) verifyEmail(w http.ResponseWriter, r *http.Request, project string) error {
var input struct {
Token string `json:"token"`
}
if !emailBody(w, r, &input) {
return nil
}
if !tokenPattern.MatchString(input.Token) {
return reject(w, 400, "invalid_verification")
}
allowed, err := s.rateLimit(r.Context(), "verify:"+project+":"+digest(input.Token), 10)
if err != nil {
return err
}
if !allowed {
return reject(w, 429, "rate_limited")
}
tx, err := s.db.BeginTx(r.Context(), nil)
if err != nil {
return err
}
defer tx.Rollback()
var email, hash string
err = tx.QueryRowContext(r.Context(), "SELECT email FROM email_registrations WHERE project=$1 AND token_hash=$2 AND expires_at>now()", project, digest(input.Token)).Scan(&email)
if errors.Is(err, sql.ErrNoRows) {
return reject(w, 400, "invalid_verification")
}
if err != nil {
return err
}
if _, err = tx.ExecContext(r.Context(), "SELECT pg_advisory_xact_lock(hashtextextended($1,0))", "email:"+project+":"+email); err != nil {
return err
}
err = tx.QueryRowContext(r.Context(), `
DELETE FROM email_registrations WHERE project=$1 AND token_hash=$2 AND expires_at>now() RETURNING email,password_hash
`, project, digest(input.Token)).Scan(&email, &hash)
if errors.Is(err, sql.ErrNoRows) {
return reject(w, 400, "invalid_verification")
}
if err != nil {
return err
}
var account string
err = tx.QueryRowContext(r.Context(), `
WITH identity AS(SELECT gen_random_uuid() AS id)
INSERT INTO project_accounts(project,id,email,username)
SELECT $1,id,$2,
left(COALESCE(NULLIF(regexp_replace(split_part($2,'@',1),'[^a-z0-9]','','g'),''),'user'),7)
|| '_' || replace(id::text,'-','') FROM identity RETURNING id::text
`, project, email).Scan(&account)
if err != nil {
return err
}
_, err = tx.ExecContext(r.Context(), "INSERT INTO email_credentials(project,email,account_id,password_hash) VALUES($1,$2,$3,$4)", project, email, account, hash)
if err != nil {
return err
}
session := token()
_, err = tx.ExecContext(r.Context(), "INSERT INTO project_sessions(token_hash,project,account_id,expires_at) VALUES($1,$2,$3,now()+interval '30 days')", digest(session), project, account)
if err != nil {
return err
}
if err = tx.Commit(); err != nil {
return err
}
reply(w, 201, payload{"access_token": session, "token_type": "Bearer", "expires_in": SessionIdleSeconds})
return nil
}
-75
View File
@@ -1,75 +0,0 @@
// 认证回归:数据库用例需要 PLATFORM_TEST_DATABASE_URL 指向隔离且已迁移的 fixture。
package auth
import (
"crypto/rand"
"database/sql"
"encoding/hex"
"net/http/httptest"
"net/url"
"os"
"regexp"
"strings"
"testing"
)
// TestConcurrentRegistrationAndVerification 并发重发注册与消费原验证链接,允许任一先取得邮箱锁;最终只能留下一个凭据或一个待验证记录。
func TestConcurrentRegistrationAndVerification(t *testing.T) {
dsn := os.Getenv("PLATFORM_TEST_DATABASE_URL")
if dsn == "" {
t.Skip("requires isolated integration database")
}
db, err := sql.Open("pgx", dsn)
if err != nil {
t.Fatal(err)
}
defer db.Close()
var raw [12]byte
rand.Read(raw[:])
project := "email-" + hex.EncodeToString(raw[:])
frontend, _ := url.Parse("https://app.example.com/auth/callback")
s := &service{db: db, projects: map[string]*url.URL{project: frontend}}
defer func() {
_, _ = db.Exec("DELETE FROM project_accounts WHERE project=$1", project)
_, _ = db.Exec("DELETE FROM email_registrations WHERE project=$1", project)
_, _ = db.Exec("DELETE FROM email_outbox WHERE project=$1", project)
}()
request := httptest.NewRequest("POST", "https://api.example.com/register", nil)
out := httptest.NewRecorder()
if err = s.registerEmail(out, request, project, "fixture@example.invalid", "long-fixture-password"); err != nil {
t.Fatal(err)
}
var body string
if err = db.QueryRow("SELECT body FROM email_outbox WHERE project=$1", project).Scan(&body); err != nil {
t.Fatal(err)
}
match := regexp.MustCompile(`verify_email=([A-Za-z0-9_-]{43})`).FindStringSubmatch(body)
if len(match) != 2 {
t.Fatal("missing verification link")
}
// 缓冲通道收集两条 goroutine 的结果;这里断言最终数据库一致性,不规定抢锁顺序。
done := make(chan error, 2)
go func() {
r := httptest.NewRequest("POST", "https://api.example.com/register", nil)
done <- s.registerEmail(httptest.NewRecorder(), r, project, "fixture@example.invalid", "another-fixture-password")
}()
go func() {
r := httptest.NewRequest("POST", "https://api.example.com/verify-email", strings.NewReader(`{"token":"`+match[1]+`"}`))
done <- s.verifyEmail(httptest.NewRecorder(), r, project)
}()
for range 2 {
if err := <-done; err != nil {
t.Fatal(err)
}
}
var accounts, pending int
if err = db.QueryRow("SELECT count(*) FROM email_credentials WHERE project=$1", project).Scan(&accounts); err != nil {
t.Fatal(err)
}
if err = db.QueryRow("SELECT count(*) FROM email_registrations WHERE project=$1", project).Scan(&pending); err != nil {
t.Fatal(err)
}
if accounts+pending != 1 {
t.Fatalf("concurrent registration left accounts=%d pending=%d", accounts, pending)
}
}
-75
View File
@@ -1,75 +0,0 @@
// 本文件把 Google、Slack、邮箱等提供方身份归一为项目账户,并签发一次性交换码。
package auth
import (
"context"
"database/sql"
"errors"
"net/url"
"strings"
)
// identityGrant 由已完成提供方验证的登录流程调用;subject 必须是该提供方的稳定身份。
// challenge 来自前端登录起点,后续 exchange 必须提交对应 verifier 才能换取会话。
func (s *service) identityGrant(ctx context.Context, project, provider, subject string, email *string, name, picture, challenge string) (string, error) {
// 外部资料仅作为初始显示信息:限制姓名长度,头像只接受无用户信息的 HTTPS URL。
name = strings.TrimSpace(name)
if len(name) > 160 {
name = ""
}
if u, err := url.Parse(picture); err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || len(picture) > 2048 {
picture = ""
}
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return "", err
}
// 账户、身份关联和短期 grant 同事务提交;任一步失败都不遗留半注册账户。
defer tx.Rollback()
// 事务级 advisory lock 串行化同项目、同提供方、同 subject 的首次注册;事务结束即释放。
if _, err = tx.ExecContext(ctx, "SELECT pg_advisory_xact_lock(hashtextextended($1,0))", project+":"+provider+":"+subject); err != nil {
return "", err
}
var account string
err = tx.QueryRowContext(ctx, "SELECT account_id::text FROM account_identities WHERE project=$1 AND provider=$2 AND subject=$3", project, provider, subject).Scan(&account)
// 身份不存在才建账户;不会仅凭相同邮箱自动合并不同提供方的身份。
if errors.Is(err, sql.ErrNoRows) {
var googleSubject *string
if provider == "google" {
googleSubject = &subject
}
err = tx.QueryRowContext(ctx, `
WITH identity AS(SELECT gen_random_uuid() AS id)
INSERT INTO project_accounts(project,id,google_subject,email,username,display_name,avatar_url)
SELECT $1,id,$2,$3,
left(COALESCE(NULLIF(regexp_replace(lower($4),'[^a-z0-9]','','g'),''),'user'),7)||'_'||replace(id::text,'-',''),
$4,NULLIF($5,'') FROM identity RETURNING id::text
`, project, googleSubject, email, name, picture).Scan(&account)
if err != nil {
return "", err
}
_, err = tx.ExecContext(ctx, "INSERT INTO account_identities(project,provider,subject,account_id) VALUES($1,$2,$3,$4)", project, provider, subject, account)
} else if err == nil {
// 老账户保留已有显示名/头像,只补空值;非空提供方邮箱会更新账户邮箱。
_, err = tx.ExecContext(ctx, `
UPDATE project_accounts SET email=COALESCE($3,email),
display_name=CASE WHEN display_name='' THEN $4 ELSE display_name END,
avatar_url=COALESCE(avatar_url,NULLIF($5,'')),
username=COALESCE(username,left(COALESCE(NULLIF(regexp_replace(lower($4),'[^a-z0-9]','','g'),''),'user'),7)||'_'||replace(id::text,'-','')),
updated_at=now() WHERE project=$1 AND id=$2
`, project, account, email, name, picture)
}
if err != nil {
return "", err
}
// 只落库交换码摘要,明文仅返回给回调方;一分钟期限和前端 challenge 限制兑换。
grant := token()
_, err = tx.ExecContext(ctx, "INSERT INTO login_grants VALUES($1,$2,$3,$4,now()+interval '1 minute')", digest(grant), project, account, challenge)
if err != nil {
return "", err
}
if err = tx.Commit(); err != nil {
return "", err
}
return grant, nil
}
-125
View File
@@ -1,125 +0,0 @@
// 邮件发送采用数据库 outbox:登录请求写队列,Run 后台轮询租约并通过 SMTP 投递。
package auth
import (
"context"
"crypto/tls"
"database/sql"
"errors"
"fmt"
"log"
"net"
"net/mail"
"net/smtp"
"os"
"strings"
"time"
)
// EmailConfig 是可选 SMTP 能力配置;Password 仅用于内存中的 SMTP 认证。
type EmailConfig struct {
Host, Port, Username, Password, From string
}
// EmailConfigFromEnv 允许整组缺省以关闭邮件登录;部分配置或非 465 TLS 配置会启动失败。
func EmailConfigFromEnv() (*EmailConfig, error) {
c := &EmailConfig{Host: os.Getenv("SMTP_HOST"), Port: os.Getenv("SMTP_PORT"), Username: os.Getenv("SMTP_USERNAME"), Password: os.Getenv("SMTP_PASSWORD"), From: os.Getenv("SMTP_FROM")}
if c.Host == "" && c.Port == "" && c.Username == "" && c.Password == "" && c.From == "" {
return nil, nil
}
address, err := mail.ParseAddress(c.From)
if c.Host == "" || c.Port != "465" || c.Username == "" || c.Password == "" || err != nil || address.Address != c.From || strings.ContainsAny(c.Host+c.Username+c.From, "\r\n") {
return nil, errors.New("invalid SMTP configuration; TLS port 465 and a plain sender address are required")
}
return c, nil
}
// send 同步发送一封纯文本邮件;拒绝头部换行,并用 TLS 主机名验证和连接期限约束网络操作。
// SMTP 调用不接收 context,Run 的取消要等当前发送结束或网络期限到达。
func (c *EmailConfig) send(recipient, subject, body string) error {
if strings.ContainsAny(recipient+subject, "\r\n") {
return errors.New("invalid mail headers")
}
connection, err := tls.DialWithDialer(&net.Dialer{Timeout: 10 * time.Second}, "tcp", net.JoinHostPort(c.Host, c.Port), &tls.Config{ServerName: c.Host, MinVersion: tls.VersionTLS12})
if err != nil {
return err
}
defer connection.Close()
_ = connection.SetDeadline(time.Now().Add(30 * time.Second))
client, err := smtp.NewClient(connection, c.Host)
if err != nil {
return err
}
defer client.Close()
if err = client.Auth(smtp.PlainAuth("", c.Username, c.Password, c.Host)); err != nil {
return err
}
if err = client.Mail(c.From); err != nil {
return err
}
if err = client.Rcpt(recipient); err != nil {
return err
}
writer, err := client.Data()
if err != nil {
return err
}
message := fmt.Sprintf("From: %s\r\nTo: %s\r\nSubject: %s\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\n%s\r\n", c.From, recipient, subject, body)
if _, err = writer.Write([]byte(message)); err != nil {
return err
}
if err = writer.Close(); err != nil {
return err
}
return client.Quit()
}
// Run 由进程入口启动;每三秒最多认领一封,nil 配置直接返回,取消上下文停止后续轮询。
func (c *EmailConfig) Run(ctx context.Context, db *sql.DB) {
if c == nil {
return
}
ticker := time.NewTicker(3 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
if err := c.deliver(ctx, db); err != nil && !errors.Is(err, sql.ErrNoRows) {
log.Printf("email delivery failed (%T)", err)
}
}
}
}
// deliver 用 SKIP LOCKED 避开其他 worker 正在认领的行,两分钟租约允许进程失败后重试。
// SMTP 成功与数据库标记并非同一事务;标记失败时后续可能再次投递。
func (c *EmailConfig) deliver(ctx context.Context, db *sql.DB) error {
var id, lease, recipient, subject, body string
var attempts int
err := db.QueryRowContext(ctx, `
UPDATE email_outbox SET lease_id=gen_random_uuid(),lease_until=now()+interval '2 minutes',attempts=attempts+1
WHERE id=(SELECT id FROM email_outbox WHERE sent_at IS NULL AND expires_at>now() AND attempts<10
AND available_at<=now() AND (lease_until IS NULL OR lease_until<=now())
ORDER BY available_at,id FOR UPDATE SKIP LOCKED LIMIT 1)
RETURNING id::text,lease_id::text,recipient,subject,body,attempts
`).Scan(&id, &lease, &recipient, &subject, &body, &attempts)
if err != nil {
return err
}
// lease 是本轮所有权标记;回写时匹配它,避免旧 worker 覆盖租约到期后的新认领结果。
sendErr := c.send(recipient, subject, body)
if sendErr == nil {
// 成功后清空邮件正文,减少验证码在队列中的保留;收件人和投递记录仍保留。
_, err = db.ExecContext(ctx, "UPDATE email_outbox SET sent_at=now(),body='',lease_until=NULL,lease_id=NULL WHERE id=$1 AND lease_id=$2", id, lease)
return err
}
// attempts 在认领时递增:第一次失败延迟 60 秒,指数退避最多 3840 秒,最多尝试十次。
delay := 30 * (1 << min(attempts, 7))
_, err = db.ExecContext(ctx, "UPDATE email_outbox SET available_at=now()+$3*interval '1 second',lease_until=NULL,lease_id=NULL WHERE id=$1 AND lease_id=$2", id, lease, delay)
if err != nil {
return err
}
return sendErr
}
-61
View File
@@ -1,61 +0,0 @@
// 本文件是认证与 platform/research 路由共享的会话入口:数据库同时检查项目、闲置期限和绝对期限。
package auth
import (
"context"
"database/sql"
"errors"
"net/http"
"strconv"
"strings"
)
// SessionIdleSeconds 是每次有效访问可续期的闲置窗口,绝对期限仍由数据库列限制。
const SessionIdleSeconds = 30 * 24 * 60 * 60
// SessionExpiryHeader 向客户端返回本次续期后的剩余秒数,供其更新本地会话提示。
const SessionExpiryHeader = "X-Foundry-Session-Expires-In"
// ErrInvalidSession 区分凭据无效与数据库故障,调用方可据此选择 401 或服务错误。
var ErrInvalidSession = errors.New("invalid session")
// Session 只携带项目内账户和剩余有效期;原始 bearer token 不进入返回结构。
type Session struct {
AccountID string
ExpiresIn int64
}
// AuthenticateSession atomically validates and renews a live session, bounded by
// its absolute deadline. Expired, revoked and wrong-project tokens never renew.
// AuthenticateSession 在单条 UPDATE 中检查项目、闲置和绝对期限,仅续期仍有效会话并返回剩余秒数。
func AuthenticateSession(ctx context.Context, db *sql.DB, project, authorization string) (Session, error) {
value, ok := strings.CutPrefix(authorization, "Bearer ")
if !ok || !tokenPattern.MatchString(value) {
return Session{}, ErrInvalidSession
}
// 单条 UPDATE 完成校验和续期,避免先查后写把已经撤销或过期的会话重新激活。
var session Session
err := db.QueryRowContext(ctx, `
UPDATE project_sessions
SET expires_at=LEAST(now()+interval '30 days',absolute_expires_at)
WHERE project=$1 AND token_hash=$2 AND expires_at>now() AND absolute_expires_at>now()
RETURNING account_id::text,GREATEST(0,FLOOR(EXTRACT(EPOCH FROM (expires_at-now()))))::bigint
`, project, digest(value)).Scan(&session.AccountID, &session.ExpiresIn)
// 无匹配行包含错误项目、已注销、闲置过期和绝对过期,统一隐藏具体原因。
if errors.Is(err, sql.ErrNoRows) {
return Session{}, ErrInvalidSession
}
return session, err
}
// WriteSessionHeaders 由 HTTP 调用方在写出响应体前执行;它本身不校验或续期。
func WriteSessionHeaders(w http.ResponseWriter, session Session) {
w.Header().Set(SessionExpiryHeader, strconv.FormatInt(session.ExpiresIn, 10))
}
// Authenticate preserves the existing API for clients that only need an account ID.
// Authenticate 供只需账户 ID 的旧调用方使用,同样会触发 AuthenticateSession 的续期。
func Authenticate(ctx context.Context, db *sql.DB, project, authorization string) (string, error) {
session, err := AuthenticateSession(ctx, db, project, authorization)
return session.AccountID, err
}
-156
View File
@@ -1,156 +0,0 @@
// 认证回归:数据库用例需要 PLATFORM_TEST_DATABASE_URL 指向隔离且已迁移的 fixture。
package auth
import (
"context"
"database/sql"
"encoding/json"
"net/http/httptest"
"os"
"strings"
"sync"
"testing"
"time"
_ "github.com/jackc/pgx/v5/stdlib"
)
// sessionFixture 建随机项目账户,通过 t.Cleanup 级联删除相关数据并关闭连接池。
func sessionFixture(t *testing.T) (*sql.DB, string, string) {
t.Helper()
dsn := os.Getenv("PLATFORM_TEST_DATABASE_URL")
if dsn == "" {
t.Skip("requires isolated integration database")
}
db, err := sql.Open("pgx", dsn)
if err != nil {
t.Fatal(err)
}
project := "session-" + token()[:12]
var account string
if err = db.QueryRow("INSERT INTO project_accounts(project,id) VALUES($1,gen_random_uuid()) RETURNING id::text", project).Scan(&account); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _, _ = db.Exec("DELETE FROM project_accounts WHERE project=$1", project); db.Close() })
return db, project, account
}
// TestSessionIdleAndAbsoluteExpiry 覆盖闲置/绝对过期与续期上限;过期记录的时间戳不得被认证请求更新。
func TestSessionIdleAndAbsoluteExpiry(t *testing.T) {
db, project, account := sessionFixture(t)
for _, test := range []struct {
name, idle, absolute string
valid bool
}{
{"active", "1 hour", "90 days", true},
{"idle-expired", "-1 second", "90 days", false},
{"absolute-cap", "1 hour", "2 days", true},
{"absolute-expired", "1 hour", "-1 second", false},
} {
t.Run(test.name, func(t *testing.T) {
value := token()
_, err := db.Exec("INSERT INTO project_sessions(token_hash,project,account_id,expires_at,absolute_expires_at) VALUES($1,$2,$3,now()+$4::interval,now()+$5::interval)", digest(value), project, account, test.idle, test.absolute)
if err != nil {
t.Fatal(err)
}
var before time.Time
if err := db.QueryRow("SELECT expires_at FROM project_sessions WHERE token_hash=$1", digest(value)).Scan(&before); err != nil {
t.Fatal(err)
}
session, err := AuthenticateSession(context.Background(), db, project, "Bearer "+value)
if !test.valid {
if err != ErrInvalidSession {
t.Fatalf("expired session accepted: %v", err)
}
var after time.Time
if err := db.QueryRow("SELECT expires_at FROM project_sessions WHERE token_hash=$1", digest(value)).Scan(&after); err != nil {
t.Fatal(err)
}
if !after.Equal(before) {
t.Fatal("expired session revived")
}
return
}
if err != nil || session.AccountID != account || session.ExpiresIn <= 0 || session.ExpiresIn > SessionIdleSeconds {
t.Fatalf("invalid renewal result: %+v %v", session, err)
}
var expiry, cap time.Time
if err := db.QueryRow("SELECT expires_at,absolute_expires_at FROM project_sessions WHERE token_hash=$1", digest(value)).Scan(&expiry, &cap); err != nil {
t.Fatal(err)
}
if expiry.After(cap) || (test.name == "absolute-cap" && !expiry.Equal(cap)) {
t.Fatal("absolute cap not enforced")
}
if test.name == "active" && session.ExpiresIn < SessionIdleSeconds-2 {
t.Fatal("active session did not receive 30 idle days")
}
})
}
}
// TestSessionIsolationRevocationAndConcurrentRenewal 检查错误项目与坏凭据拒绝、四个并发续期受绝对期限限制、删除后不能重新续期。
func TestSessionIsolationRevocationAndConcurrentRenewal(t *testing.T) {
db, project, account := sessionFixture(t)
value := token()
if _, err := db.Exec("INSERT INTO project_sessions(token_hash,project,account_id,expires_at,absolute_expires_at) VALUES($1,$2,$3,now()+interval '1 hour',now()+interval '2 days')", digest(value), project, account); err != nil {
t.Fatal(err)
}
for _, input := range []struct{ project, authorization string }{{"other", "Bearer " + value}, {project, "Bearer bad-token"}, {project, ""}} {
if _, err := AuthenticateSession(context.Background(), db, input.project, input.authorization); err != ErrInvalidSession {
t.Fatalf("invalid or cross-project token accepted: %v", err)
}
}
var group sync.WaitGroup
for range 4 {
group.Add(1)
go func() {
defer group.Done()
session, err := AuthenticateSession(context.Background(), db, project, "Bearer "+value)
if err != nil || session.ExpiresIn > 2*86400 {
t.Errorf("concurrent renewal escaped cap: %+v %v", session, err)
}
}()
}
group.Wait()
if _, err := db.Exec("DELETE FROM project_sessions WHERE token_hash=$1", digest(value)); err != nil {
t.Fatal(err)
}
if _, err := AuthenticateSession(context.Background(), db, project, "Bearer "+value); err != ErrInvalidSession {
t.Fatal("revoked session renewed")
}
}
// TestOAuthExchangeIssuesLongLivedSessionAndMeReturnsRemainingLifetime 从真实 grant 兑换会话,检查三十天闲置/九十天绝对期限,以及 me 响应的续期头。
func TestOAuthExchangeIssuesLongLivedSessionAndMeReturnsRemainingLifetime(t *testing.T) {
db, project, account := sessionFixture(t)
code, verifier := token(), token()
_, err := db.Exec("INSERT INTO login_grants(token_hash,project,account_id,frontend_challenge,expires_at) VALUES($1,$2,$3,$4,now()+interval '1 minute')", digest(code), project, account, digest(verifier))
if err != nil {
t.Fatal(err)
}
s := &service{db: db}
r := httptest.NewRequest("POST", "/exchange", nil)
r.Header.Set("X-Foundry-Code", code)
r.Header.Set("X-Foundry-Verifier", verifier)
out := httptest.NewRecorder()
if err = s.exchange(out, r, project); err != nil || out.Code != 200 {
t.Fatalf("exchange: %d %v", out.Code, err)
}
var result struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
}
if err = json.Unmarshal(out.Body.Bytes(), &result); err != nil || result.ExpiresIn != SessionIdleSeconds {
t.Fatal("incorrect login lifetime")
}
var idle, absolute float64
if err = db.QueryRow("SELECT EXTRACT(EPOCH FROM(expires_at-created_at)),EXTRACT(EPOCH FROM(absolute_expires_at-created_at)) FROM project_sessions WHERE token_hash=$1", digest(result.AccessToken)).Scan(&idle, &absolute); err != nil || idle < SessionIdleSeconds-2 || absolute != 90*86400 {
t.Fatalf("wrong session deadlines: %f %f %v", idle, absolute, err)
}
r = httptest.NewRequest("GET", "/me", strings.NewReader(""))
r.Header.Set("Authorization", "Bearer "+result.AccessToken)
out = httptest.NewRecorder()
if err = s.account(out, r, project, false); err != nil || out.Header().Get(SessionExpiryHeader) == "" {
t.Fatal("missing renewal header")
}
}
-239
View File
@@ -1,239 +0,0 @@
// Slack OIDC 登录验证独立 ID token,再复用 identityGrant 和前端 grant 兑换协议。
package auth
import (
"context"
"crypto"
"crypto/rsa"
"crypto/sha256"
"database/sql"
"encoding/base64"
"encoding/json"
"errors"
"math/big"
"net/http"
"net/url"
"os"
"strings"
"sync"
"time"
)
// SlackConfig 保存可选客户端凭据以及由 mu 保护的签名公钥缓存。
type SlackConfig struct {
ClientID, Secret, RedirectURI string
mu sync.Mutex
keys map[string]*rsa.PublicKey
fetchedAt time.Time
}
// SlackConfigFromEnv 允许整组缺省以关闭 Slack;只配置一半会阻止服务启动。
func SlackConfigFromEnv(redirect string) (*SlackConfig, error) {
id, secret := os.Getenv("SLACK_CLIENT_ID"), os.Getenv("SLACK_CLIENT_SECRET")
if id == "" && secret == "" {
return nil, nil
}
if id == "" || secret == "" || strings.ContainsAny(id+secret, "\r\n") {
return nil, errors.New("Slack requires client ID and secret")
}
return &SlackConfig{ClientID: id, Secret: secret, RedirectURI: redirect}, nil
}
// slackClaims 仅在验签、发行方/受众/时间和 nonce 校验后用于账户身份。
type slackClaims struct {
Issuer string `json:"iss"`
Subject string `json:"sub"`
Audience string `json:"aud"`
Expires int64 `json:"exp"`
Issued int64 `json:"iat"`
Nonce string `json:"nonce"`
Team string `json:"https://slack.com/team_id"`
Email *string `json:"email"`
Verified bool `json:"email_verified"`
Name string `json:"name"`
Picture string `json:"picture"`
}
// slackKey 在互斥锁内加载并缓存 JWKS 一分钟;缓存期遇到未知 kid 直接拒绝,避免重复拉取。
func (s *service) slackKey(ctx context.Context, kid string) (*rsa.PublicKey, error) {
c := s.slack
c.mu.Lock()
defer c.mu.Unlock()
if time.Since(c.fetchedAt) < time.Minute {
if key := c.keys[kid]; key != nil {
return key, nil
}
return nil, errors.New("unknown Slack signing key")
}
var document struct {
Keys []struct {
Type string `json:"kty"`
ID string `json:"kid"`
Algorithm string `json:"alg"`
Use string `json:"use"`
N string `json:"n"`
E string `json:"e"`
}
}
if err := s.googleJSON(ctx, "GET", "https://slack.com/openid/connect/keys", nil, "", &document); err != nil {
return nil, err
}
// 只接收可用于 RS256 签名的 RSA 公钥,并约束模数和指数大小。
keys := map[string]*rsa.PublicKey{}
for _, key := range document.Keys {
n, nErr := base64.RawURLEncoding.DecodeString(key.N)
e, eErr := base64.RawURLEncoding.DecodeString(key.E)
if key.Type != "RSA" || (key.Algorithm != "" && key.Algorithm != "RS256") || (key.Use != "" && key.Use != "sig") || nErr != nil || eErr != nil || len(e) > 4 {
continue
}
modulus := new(big.Int).SetBytes(n)
exponent := new(big.Int).SetBytes(e).Int64()
if modulus.BitLen() < 2048 || modulus.BitLen() > 8192 || exponent < 3 || exponent > 2147483647 || exponent%2 == 0 {
continue
}
keys[key.ID] = &rsa.PublicKey{N: modulus, E: int(exponent)}
}
c.keys, c.fetchedAt = keys, time.Now()
if key := keys[kid]; key != nil {
return key, nil
}
return nil, errors.New("unknown Slack signing key")
}
// verifySlack 限制 token 长度与算法,先验签再信任 payload;nonce 将身份绑定到本次登录。
func (s *service) verifySlack(ctx context.Context, value, nonce string) (slackClaims, error) {
var claims slackClaims
invalid := errors.New("invalid Slack identity token")
if len(value) > 32768 {
return claims, invalid
}
parts := strings.Split(value, ".")
if len(parts) != 3 {
return claims, invalid
}
header, err := base64.RawURLEncoding.DecodeString(parts[0])
var h struct {
Algorithm string `json:"alg"`
ID string `json:"kid"`
}
if err != nil || json.Unmarshal(header, &h) != nil || h.Algorithm != "RS256" || h.ID == "" {
return claims, invalid
}
key, err := s.slackKey(ctx, h.ID)
if err != nil {
return claims, err
}
signature, err := base64.RawURLEncoding.DecodeString(parts[2])
sum := sha256.Sum256([]byte(parts[0] + "." + parts[1]))
if err != nil || rsa.VerifyPKCS1v15(key, crypto.SHA256, sum[:], signature) != nil {
return claims, invalid
}
body, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil || json.Unmarshal(body, &claims) != nil {
return claims, invalid
}
now := time.Now().Unix()
if claims.Issuer != "https://slack.com" || claims.Audience != s.slack.ClientID || claims.Expires <= now ||
claims.Issued <= 0 || claims.Issued > now+60 || claims.Expires <= claims.Issued || claims.Nonce != nonce ||
claims.Subject == "" || len(claims.Subject) > 128 || claims.Team == "" || len(claims.Team) > 128 ||
strings.ContainsAny(claims.Subject+claims.Team, ":\r\n") {
return claims, invalid
}
if !claims.Verified {
claims.Email = nil
}
return claims, nil
}
// startSlack 写十分钟尝试和 OIDC nonce,Cookie 采用 SameSite=None 以接收跨站 POST 回调。
func (s *service) startSlack(w http.ResponseWriter, r *http.Request, project string) error {
if s.slack == nil {
return reject(w, 503, "slack_not_configured")
}
challenge := r.URL.Query().Get("challenge")
if !tokenPattern.MatchString(challenge) {
return reject(w, 400, "invalid_challenge")
}
state, browser, nonce := token(), token(), token()
_, err := s.db.ExecContext(r.Context(), `
INSERT INTO oauth_attempts(state_hash,browser_hash,project,frontend_challenge,google_verifier,expires_at,provider,oidc_nonce)
VALUES($1,$2,$3,$4,'',now()+interval '10 minutes','slack',$5)
`, digest(state), digest(browser), project, challenge, nonce)
if err != nil {
return err
}
cookie := oauthCookie(state, browser, 600)
cookie.SameSite = http.SameSiteNoneMode
http.SetCookie(w, cookie)
query := url.Values{"response_type": {"code"}, "scope": {"openid profile email"}, "client_id": {s.slack.ClientID}, "state": {state}, "nonce": {nonce}, "redirect_uri": {s.slack.RedirectURI}}
http.Redirect(w, r, "https://slack.com/openid/connect/authorize?"+query.Encode(), 302)
return nil
}
// slackCallback 接受 GET/POST,先一次性消费浏览器绑定的尝试,再向 Slack 兑换 ID token。
func (s *service) slackCallback(w http.ResponseWriter, r *http.Request) error {
if s.slack == nil {
return reject(w, 503, "slack_not_configured")
}
if r.Method != http.MethodGet && r.Method != http.MethodPost {
return reject(w, 405, "method_not_allowed")
}
r.Body = http.MaxBytesReader(w, r.Body, 16384)
if r.ParseForm() != nil {
return reject(w, 400, "invalid_callback")
}
state := r.Form.Get("state")
cookie, err := r.Cookie(oauthCookie(state, "", 0).Name)
if !tokenPattern.MatchString(state) || err != nil || !tokenPattern.MatchString(cookie.Value) {
return reject(w, 400, "invalid_state")
}
var project, challenge, nonce string
err = s.db.QueryRowContext(r.Context(), `
DELETE FROM oauth_attempts WHERE state_hash=$1 AND browser_hash=$2 AND expires_at>now() AND provider='slack'
RETURNING project,frontend_challenge,oidc_nonce
`, digest(state), digest(cookie.Value)).Scan(&project, &challenge, &nonce)
if errors.Is(err, sql.ErrNoRows) {
return reject(w, 400, "invalid_state")
}
if err != nil {
return err
}
frontend := s.projects[project]
if frontend == nil {
return reject(w, 400, "invalid_state")
}
expired := oauthCookie(state, "", -1)
expired.SameSite = http.SameSiteNoneMode
http.SetCookie(w, expired)
destination := *frontend
if r.Form.Get("code") == "" || r.Form.Has("error") {
destination.Fragment = "error=slack_login_cancelled"
http.Redirect(w, r, destination.String(), 302)
return nil
}
var tokens struct {
OK bool `json:"ok"`
IDToken string `json:"id_token"`
}
err = s.googleJSON(r.Context(), "POST", "https://slack.com/api/openid.connect.token", url.Values{
"code": {r.Form.Get("code")}, "client_id": {s.slack.ClientID}, "client_secret": {s.slack.Secret}, "redirect_uri": {s.slack.RedirectURI}, "grant_type": {"authorization_code"},
}, "", &tokens)
if err != nil {
return err
}
if !tokens.OK || tokens.IDToken == "" {
return errors.New("Slack token exchange failed")
}
claims, err := s.verifySlack(r.Context(), tokens.IDToken, nonce)
if err != nil {
return err
}
// 团队和用户共同构成 subject;verifySlack 已拒绝冒号,避免拼接身份产生歧义。
grant, err := s.identityGrant(r.Context(), project, "slack", claims.Team+":"+claims.Subject, claims.Email, claims.Name, claims.Picture, challenge)
if err != nil {
return err
}
destination.Fragment = "code=" + grant
http.Redirect(w, r, destination.String(), 302)
return nil
}
-231
View File
@@ -1,231 +0,0 @@
// 认证回归:数据库用例需要 PLATFORM_TEST_DATABASE_URL 指向隔离且已迁移的 fixture。
package auth
import (
"context"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"database/sql"
"encoding/base64"
"encoding/hex"
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"os"
"strings"
"testing"
"time"
_ "github.com/jackc/pgx/v5/stdlib"
)
// signIdentity 为 fixture kid 生成 RS256 JWT;测试公钥缓存在内存,不访问 Slack JWKS。
func signIdentity(t *testing.T, key *rsa.PrivateKey, claims slackClaims) string {
t.Helper()
header := base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"RS256","kid":"fixture"}`))
body, err := json.Marshal(claims)
if err != nil {
t.Fatal(err)
}
value := header + "." + base64.RawURLEncoding.EncodeToString(body)
hash := sha256.Sum256([]byte(value))
sig, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, hash[:])
if err != nil {
t.Fatal(err)
}
return value + "." + base64.RawURLEncoding.EncodeToString(sig)
}
// TestSlackIdentityVerification 使用本地 RSA 私钥签发样本,分别破坏发行方、受众、时间、nonce、签名及算法,仅有效样本可通过。
func TestSlackIdentityVerification(t *testing.T) {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal(err)
}
s := &service{slack: &SlackConfig{ClientID: "fixture", keys: map[string]*rsa.PublicKey{"fixture": &key.PublicKey}, fetchedAt: time.Now()}}
good := slackClaims{Issuer: "https://slack.com", Subject: "U123", Team: "T123", Audience: "fixture", Expires: time.Now().Add(time.Minute).Unix(), Issued: time.Now().Unix(), Nonce: "nonce"}
for _, name := range []string{"valid", "issuer", "audience", "expired", "nonce", "signature", "algorithm"} {
t.Run(name, func(t *testing.T) {
claims := good
switch name {
case "issuer":
claims.Issuer = "https://attacker.invalid"
case "audience":
claims.Audience = "other-client"
case "expired":
claims.Expires = time.Now().Add(-time.Minute).Unix()
case "nonce":
claims.Nonce = "wrong"
}
value := signIdentity(t, key, claims)
if name == "signature" {
parts := strings.Split(value, ".")
sig, _ := base64.RawURLEncoding.DecodeString(parts[2])
sig[0] ^= 1
parts[2] = base64.RawURLEncoding.EncodeToString(sig)
value = strings.Join(parts, ".")
}
if name == "algorithm" {
parts := strings.Split(value, ".")
parts[0] = base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"none","kid":"fixture"}`))
value = strings.Join(parts, ".")
}
_, err := s.verifySlack(context.Background(), value, "nonce")
if (err == nil) != (name == "valid") {
t.Fatalf("unexpected verification result %v", err)
}
})
}
}
// TestSlackCallbackAndExchange 使用临时 HTTP 上游和真实测试库走 Slack 起点、POST 回调、grant 兑换;拒绝回调重放并保留用户已选资料。
func TestSlackCallbackAndExchange(t *testing.T) {
dsn := os.Getenv("PLATFORM_TEST_DATABASE_URL")
if dsn == "" {
t.Skip("requires isolated integration database")
}
db, err := sql.Open("pgx", dsn)
if err != nil {
t.Fatal(err)
}
defer db.Close()
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal(err)
}
var value [12]byte
rand.Read(value[:])
project := "slack-" + hex.EncodeToString(value[:])
defer db.Exec("DELETE FROM project_accounts WHERE project=$1", project)
frontend, _ := url.Parse("https://app.example.com/auth/callback")
config := &SlackConfig{ClientID: "fixture", Secret: "fixture-secret", RedirectURI: "https://api.example.com/auth/slack/callback", keys: map[string]*rsa.PublicKey{"fixture": &key.PublicKey}, fetchedAt: time.Now()}
verifier := token()
var nonce string
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
t.Error("unexpected Slack request method")
}
_ = r.ParseForm()
if r.Form.Get("client_id") != "fixture" || r.Form.Get("client_secret") != "fixture-secret" {
t.Error("incorrect Slack client credentials")
}
claims := slackClaims{Issuer: "https://slack.com", Subject: "U123", Team: "T123", Audience: "fixture", Expires: time.Now().Add(time.Minute).Unix(), Issued: time.Now().Unix(), Nonce: nonce, Name: "Slack User"}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "id_token": signIdentity(t, key, claims)})
}))
defer upstream.Close()
s := &service{db: db, projects: map[string]*url.URL{project: frontend}, slack: config, google: &http.Client{Transport: rewriteTransport{destination: upstream.URL}}}
start := httptest.NewRequest("GET", "https://api.example.com/projects/"+project+"/auth/slack?challenge="+digest(verifier), nil)
out := httptest.NewRecorder()
if err = s.startSlack(out, start, project); err != nil {
t.Fatal(err)
}
if out.Code != 302 {
t.Fatalf("start status %d", out.Code)
}
location, _ := url.Parse(out.Header().Get("Location"))
nonce = location.Query().Get("nonce")
state := location.Query().Get("state")
if nonce == "" || state == "" {
t.Fatal("missing state or nonce")
}
cookies := out.Result().Cookies()
if len(cookies) != 1 || cookies[0].SameSite != http.SameSiteNoneMode || !cookies[0].Secure || !cookies[0].HttpOnly {
t.Fatal("incorrect Slack browser binding cookie")
}
body := url.Values{"state": {state}, "code": {"fixture-code"}}
callback := func() *httptest.ResponseRecorder {
r := httptest.NewRequest("POST", config.RedirectURI, strings.NewReader(body.Encode()))
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
r.AddCookie(cookies[0])
w := httptest.NewRecorder()
if err := s.slackCallback(w, r); err != nil {
t.Fatal(err)
}
return w
}
success := callback()
if success.Code != 302 {
t.Fatalf("callback status %d %s", success.Code, success.Body.String())
}
destination, _ := url.Parse(success.Header().Get("Location"))
fragment, _ := url.ParseQuery(destination.Fragment)
grant := fragment.Get("code")
if !tokenPattern.MatchString(grant) {
t.Fatal("callback missing one-time exchange code")
}
if replay := callback(); replay.Code != 400 {
t.Fatal("Slack callback replay accepted")
}
request := httptest.NewRequest("POST", "https://api.example.com/projects/"+project+"/auth/exchange", nil)
request.Header.Set("X-Foundry-Code", grant)
request.Header.Set("X-Foundry-Verifier", verifier)
exchange := httptest.NewRecorder()
if err = s.exchange(exchange, request, project); err != nil {
t.Fatal(err)
}
if exchange.Code != 200 {
t.Fatalf("exchange status %d", exchange.Code)
}
var account, username, name string
err = db.QueryRow("SELECT a.id::text,a.username,a.display_name FROM project_accounts a JOIN account_identities i ON (i.project,i.account_id)=(a.project,a.id) WHERE a.project=$1 AND i.provider='slack' AND i.subject='T123:U123'", project).Scan(&account, &username, &name)
if err != nil || username == "" || name != "Slack User" {
t.Fatalf("Slack profile prefill failed %v", err)
}
_, err = db.Exec("UPDATE project_accounts SET username='chosen-name',display_name='Chosen name' WHERE project=$1 AND id=$2", project, account)
if err != nil {
t.Fatal(err)
}
if _, err = s.identityGrant(context.Background(), project, "slack", "T123:U123", nil, "New Slack Name", "", digest(verifier)); err != nil {
t.Fatal(err)
}
if err = db.QueryRow("SELECT username,display_name FROM project_accounts WHERE project=$1 AND id=$2", project, account).Scan(&username, &name); err != nil {
t.Fatal(err)
}
if username != "chosen-name" || name != "Chosen name" {
t.Fatal("provider login overwrote chosen profile")
}
}
// rewriteTransport 只把测试外部调用改写到本地上游,保留路径和请求上下文。
type rewriteTransport struct{ destination string }
// RoundTrip 克隆请求后改目标,避免修改被测函数持有的原请求对象。
func (t rewriteTransport) RoundTrip(r *http.Request) (*http.Response, error) {
cloned := r.Clone(r.Context())
target, _ := url.Parse(t.destination)
cloned.URL.Scheme, cloned.URL.Host = target.Scheme, target.Host
return http.DefaultTransport.RoundTrip(cloned)
}
// TestGoogleIdentityKeepsLegacyAccount 依赖迁移 fixture 的旧 Google 身份与会话,验证新身份归一流程仍使用原账户且不删除旧会话。
func TestGoogleIdentityKeepsLegacyAccount(t *testing.T) {
dsn := os.Getenv("PLATFORM_TEST_DATABASE_URL")
if dsn == "" {
t.Skip("requires isolated integration database")
}
db, err := sql.Open("pgx", dsn)
if err != nil {
t.Fatal(err)
}
defer db.Close()
s := &service{db: db}
grant, err := s.identityGrant(context.Background(), "fixture", "google", "existing-google", nil, "Existing Google User", "", digest(token()))
if err != nil {
t.Fatal(err)
}
var account string
if err = db.QueryRow("SELECT account_id::text FROM login_grants WHERE project='fixture' AND token_hash=$1", digest(grant)).Scan(&account); err != nil {
t.Fatal(err)
}
if account != "00000000-0000-0000-0000-000000000001" {
t.Fatal("legacy Google identity changed account ID")
}
var count int
if err = db.QueryRow("SELECT count(*) FROM project_sessions WHERE project='fixture' AND token_hash='existing-session'").Scan(&count); err != nil || count != 1 {
t.Fatalf("existing Google session was lost %v", err)
}
}
-167
View File
@@ -1,167 +0,0 @@
// 画布 AI 的私有 IPC 客户端与模型目录:平台侧只看到稳定模型 ID,执行后端保留在 worker 内。
package codex
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"io"
"net"
"net/http"
"os"
"sort"
"strings"
"time"
)
// CanvasInputLimit 限制提示词字节数;图片另按解码后的总字节限制。
const CanvasInputLimit = 1 << 20
// CanvasModel 是过滤后的模型能力快照;Backend 不序列化,仅供 worker 启动 CLI。
type CanvasModel struct {
ID string `json:"id"`
Label string `json:"label"`
Provider string `json:"provider"`
InputModalities []string `json:"input_modalities"`
OutputModalities []string `json:"output_modalities"`
Available bool `json:"available"`
MaxExecutionMS int `json:"max_execution_ms"`
MaxInputBytes int `json:"max_input_bytes"`
ParametersSchema map[string]any `json:"parameters_schema"`
Backend string `json:"-"`
}
// Only curated catalog fields leave the worker. Raw CLI cache metadata,
// local paths, authentication files and backend configuration stay private.
// workerCanvasModels 读取 worker 本地缓存,只公布 list 可见且支持文本/图像输入的条目。
func workerCanvasModels() ([]CanvasModel, error) {
raw, err := os.ReadFile("/home/node/.codex/models_cache.json")
if err != nil {
return nil, err
}
var cache struct {
Models []struct {
Slug string `json:"slug"`
Label string `json:"display_name"`
Visibility string `json:"visibility"`
Inputs []string `json:"input_modalities"`
} `json:"models"`
}
if err = json.Unmarshal(raw, &cache); err != nil {
return nil, err
}
result := []CanvasModel{}
for _, entry := range cache.Models {
if entry.Visibility != "list" || entry.Slug == "" || strings.HasPrefix(entry.Slug, "-") || len(entry.Slug) > 128 {
continue
}
// 稳定散列生成公开 ID;标签可展示,实际 slug 不作为公开 Backend 字段输出。
sum := sha256.Sum256([]byte("codex-cli/" + entry.Slug))
inputs := []string{}
for _, value := range entry.Inputs {
if value == "text" || value == "image" {
inputs = append(inputs, value)
}
}
if len(inputs) == 0 {
continue
}
label := entry.Label
if label == "" {
label = entry.Slug
}
if len(label) > 128 {
label = entry.Slug
}
result = append(result, CanvasModel{ID: "codex-" + hex.EncodeToString(sum[:16]), Label: label, Provider: "codex-cli", InputModalities: inputs, OutputModalities: []string{"text"}, Available: true, MaxExecutionMS: 90000, MaxInputBytes: CanvasInputLimit, ParametersSchema: map[string]any{"type": "object", "properties": map[string]any{}, "additionalProperties": false}, Backend: entry.Slug})
}
// 图片输出能力必须显式列入已验证后端名单,不能根据支持图片输入推断支持图片生成。
verified := map[string]bool{}
for _, id := range strings.Split(os.Getenv("FOUNDRY_CANVAS_IMAGE_MODELS"), ",") {
id = strings.TrimSpace(id)
if id != "" {
verified[id] = true
}
}
textModels := append([]CanvasModel{}, result...)
for _, model := range textModels {
if !verified[model.Backend] {
continue
}
sum := sha256.Sum256([]byte("codex-cli/" + model.Backend + "/image"))
model.ID = "codex-" + hex.EncodeToString(sum[:16])
model.Label += " · Image"
model.OutputModalities = []string{"image"}
model.MaxExecutionMS = 180000
result = append(result, model)
}
sort.Slice(result, func(i, j int) bool { return result[i].ID < result[j].ID })
return result, nil
}
// CanvasClient 通过固定 Unix socket 发送 HTTP;URL 主机名只是协议占位符,不进行 DNS 连接。
type CanvasClient struct{ client *http.Client }
// NewCanvasClient 在未配置 socket 时返回 nil,调用方法会转换为明确的不可用错误。
func NewCanvasClient(socket string) *CanvasClient {
if socket == "" {
return nil
}
transport := &http.Transport{DisableKeepAlives: true, DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
return (&net.Dialer{}).DialContext(ctx, "unix", socket)
}}
return &CanvasClient{client: &http.Client{Transport: transport, Timeout: 182 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}
}
// Models 限制目录响应为 256 KiB,只接受成功状态和完整 JSON,隐藏 worker 内部失败原因。
func (c *CanvasClient) Models(ctx context.Context) ([]CanvasModel, error) {
if c == nil {
return nil, errors.New("codex_unavailable")
}
request, err := http.NewRequestWithContext(ctx, "GET", "http://codex/canvas/models", nil)
if err != nil {
return nil, err
}
response, err := c.client.Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode != 200 {
return nil, errors.New("codex_unavailable")
}
raw, err := io.ReadAll(io.LimitReader(response.Body, 256<<10))
if err != nil {
return nil, err
}
var result struct {
Models []CanvasModel `json:"models"`
}
if err = json.Unmarshal(raw, &result); err != nil {
return nil, err
}
return result.Models, nil
}
// CanvasTask 在 platform 调度器与 worker 之间传递提示、模型及可选图片;当前参数对象必须为空。
type CanvasTask struct {
OutputModality string `json:"output_modality,omitempty"`
Images []CanvasImage `json:"images,omitempty"`
ModelID string `json:"model_id"`
Prompt string `json:"prompt"`
Parameters map[string]any `json:"parameters"`
}
// Generate 是只需文本的兼容入口;复用结构化输出校验,并拒绝图片结果。
func (c *CanvasClient) Generate(ctx context.Context, input CanvasTask) (string, error) {
output, err := c.GenerateOutput(ctx, input)
if err != nil {
return "", err
}
if output.Kind != "text" {
return "", errors.New("model_incompatible")
}
return output.Text, nil
}
-111
View File
@@ -1,111 +0,0 @@
// 画布生成的结构化 IPC 输出;图片以字节传到核心,再由平台资产流程验证和持久化。
package codex
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
)
// CanvasImageBytesLimit 限制原始图片总字节,响应上限另为 JSON/base64 编码留出空间。
const CanvasImageBytesLimit = 20 << 20
const canvasArtifactResponseLimit = 32 << 20
// CanvasImage 的 Data 在 JSON 中编码为 base64,仅用于私有 Unix 通道。
type CanvasImage struct {
MIME string `json:"mime_type"`
Data []byte `json:"data"`
}
// CanvasOutput 用 Kind 区分文本和图片,由 GenerateOutput 再校验形态与请求模态相符。
type CanvasOutput struct {
Kind string `json:"kind"`
Text string `json:"text,omitempty"`
Image *CanvasImage `json:"image,omitempty"`
}
// Encoded image bytes exist only on the private Unix IPC channel. Public Canvas
// jobs expose stable asset IDs/URLs and never serialize these bytes to browsers.
// GenerateOutput 先检查输入预算,再发送 IPC;映射稳定错误码,兼容旧 worker 的 result 文本字段。
func (c *CanvasClient) GenerateOutput(ctx context.Context, input CanvasTask) (CanvasOutput, error) {
if c == nil {
return CanvasOutput{}, errors.New("codex_unavailable")
}
if len(input.Prompt) > CanvasInputLimit || len(input.Images) > 4 {
return CanvasOutput{}, errors.New("context_too_large")
}
total := 0
for _, image := range input.Images {
total += len(image.Data)
}
if total > CanvasImageBytesLimit {
return CanvasOutput{}, errors.New("context_too_large")
}
raw, err := json.Marshal(input)
if err != nil {
return CanvasOutput{}, err
}
request, err := http.NewRequestWithContext(ctx, "POST", "http://codex/canvas/exec", bytes.NewReader(raw))
if err != nil {
return CanvasOutput{}, err
}
response, err := c.client.Do(request)
if err != nil {
return CanvasOutput{}, err
}
defer response.Body.Close()
// 多读一字节区分刚好达到上限与实际超限,防止截断响应被当成成功结果。
raw, err = io.ReadAll(io.LimitReader(response.Body, canvasArtifactResponseLimit+1))
if err != nil || len(raw) > canvasArtifactResponseLimit {
return CanvasOutput{}, errors.New("generation_failed")
}
var result struct {
Result string `json:"result"`
Output *CanvasOutput `json:"output"`
Error string `json:"error"`
}
if json.Unmarshal(raw, &result) != nil {
return CanvasOutput{}, errors.New("generation_failed")
}
if response.StatusCode != 200 {
switch result.Error {
case "codex_timeout":
return CanvasOutput{}, errors.New("generation_timeout")
case "codex_busy":
if response.StatusCode == 429 {
return CanvasOutput{}, errors.New("codex_busy")
}
return CanvasOutput{}, errors.New("generation_failed")
case "context_too_large":
return CanvasOutput{}, errors.New("context_too_large")
case "model_unavailable":
return CanvasOutput{}, errors.New("model_unavailable")
default:
return CanvasOutput{}, errors.New("generation_failed")
}
}
// 旧响应只允许回退到文本;图片请求缺少结构化图片时必须失败。
if result.Output == nil {
if input.OutputModality == "image" {
return CanvasOutput{}, errors.New("generation_failed")
}
return CanvasOutput{Kind: "text", Text: result.Result}, nil
}
output := *result.Output
switch output.Kind {
case "text":
if len(output.Text) > maxOutput || output.Image != nil || input.OutputModality == "image" {
return CanvasOutput{}, errors.New("generation_failed")
}
case "image":
if output.Image == nil || len(output.Image.Data) == 0 || len(output.Image.Data) > CanvasImageBytesLimit || input.OutputModality != "image" {
return CanvasOutput{}, errors.New("generation_failed")
}
default:
return CanvasOutput{}, errors.New("generation_failed")
}
return output, nil
}
-66
View File
@@ -1,66 +0,0 @@
// 本文件用临时目录和固定事件验证产物隔离及完成判定,不启动 CLI 或真实模型。
package codex
import (
"encoding/base64"
"os"
"path/filepath"
"testing"
)
// TestCanvasArtifactDirectoryIsolation 拒绝目录外图片、多张图片和软链接,只接收生成目录内唯一图片。
func TestCanvasArtifactDirectoryIsolation(t *testing.T) {
root := t.TempDir()
generated := filepath.Join(root, "generated_images")
if err := os.Mkdir(generated, 0700); err != nil {
t.Fatal(err)
}
// A minimal PNG header is sufficient for the worker's transport sniff. Core
// performs full decode/dimension validation before accepting it as an asset.
encoded, _ := base64.StdEncoding.DecodeString("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+j1WQAAAAASUVORK5CYII=")
if err := os.WriteFile(filepath.Join(root, "unrelated.png"), encoded, 0600); err != nil {
t.Fatal(err)
}
if _, err := readCanvasGeneratedImage(generated); err == nil {
t.Fatal("unrelated image used as generated output")
}
if err := os.WriteFile(filepath.Join(generated, "result.png"), encoded, 0600); err != nil {
t.Fatal(err)
}
result, err := readCanvasGeneratedImage(generated)
if err != nil || result.MIME != "image/png" || len(result.Data) != len(encoded) {
t.Fatalf("generated output: %v", err)
}
if err := os.WriteFile(filepath.Join(generated, "second.png"), encoded, 0600); err != nil {
t.Fatal(err)
}
if _, err := readCanvasGeneratedImage(generated); err == nil {
t.Fatal("multiple images silently dropped")
}
if err := os.Remove(filepath.Join(generated, "second.png")); err != nil {
t.Fatal(err)
}
if err := os.Remove(filepath.Join(generated, "result.png")); err != nil {
t.Fatal(err)
}
if err := os.Symlink(filepath.Join(root, "unrelated.png"), filepath.Join(generated, "escape.png")); err != nil {
t.Fatal(err)
}
if _, err := readCanvasGeneratedImage(generated); err == nil {
t.Fatal("symlink escaped job output directory")
}
}
// TestCanvasAgentCompletionRequiresSuccessfulTurn 拒绝仅有部分文本或完成后报错的流,接受成功结束的流。
func TestCanvasAgentCompletionRequiresSuccessfulTurn(t *testing.T) {
if _, ok := canvasAgentText([]byte("{\"type\":\"item.completed\",\"item\":{\"type\":\"agent_message\",\"text\":\"partial\"}}\n")); ok {
t.Fatal("partial generation accepted")
}
if _, ok := canvasAgentText([]byte("{\"type\":\"turn.completed\"}\n{\"type\":\"error\"}\n")); ok {
t.Fatal("failed generation accepted")
}
text, ok := canvasAgentText([]byte("{\"type\":\"item.completed\",\"item\":{\"type\":\"agent_message\",\"text\":\"done\"}}\n{\"type\":\"turn.completed\"}\n"))
if !ok || text != "done" {
t.Fatal("successful generation rejected")
}
}
-209
View File
@@ -1,209 +0,0 @@
// worker 侧画布执行:每次任务新建临时 CODEX_HOME,按模态启动 CLI 并提取完成结果。
package codex
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io/fs"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
"time"
)
// executeCanvasTask 由共享执行槽保护;模型已从目录选出,但仍须核对请求模态和输入图片。
func executeCanvasTask(w http.ResponseWriter, r *http.Request, input CanvasTask, model CanvasModel) {
imageOutput := input.OutputModality == "image"
if input.OutputModality != "" && input.OutputModality != "text" && !imageOutput {
fail(w, 400, "invalid_ai_request")
return
}
if imageOutput != (len(model.OutputModalities) == 1 && model.OutputModalities[0] == "image") {
fail(w, 422, "model_incompatible")
return
}
duration := 90 * time.Second
if imageOutput {
duration = 180 * time.Second
}
ctx, cancel := context.WithTimeout(r.Context(), duration)
defer cancel()
// 临时目录承载认证软链接、输入图片和生成产物;成功与所有失败路径都由 defer 删除。
job, err := os.MkdirTemp("", "foundry-canvas-")
if err != nil {
fail(w, 503, "codex_unavailable")
return
}
defer os.RemoveAll(job)
home := filepath.Join(job, "home")
if os.Mkdir(home, 0700) != nil || os.Symlink("/home/node/.codex/auth.json", filepath.Join(home, "auth.json")) != nil {
fail(w, 503, "codex_unavailable")
return
}
// 关闭 shell、应用、插件等能力;文本模型还关闭图片生成,画布模式忽略用户配置与规则。
args := []string{"--ask-for-approval", "never", "--disable", "shell_tool", "--disable", "apps", "--disable", "plugins", "--disable", "multi_agent", "--disable", "hooks", "--disable", "memories", "-c", `web_search="disabled"`}
if !imageOutput {
args = append(args, "--disable", "image_generation")
}
args = append(args, "exec", "--json", "--sandbox", "read-only", "--skip-git-repo-check", "--ephemeral", "--ignore-user-config", "--ignore-rules", "--model", model.Backend)
// 对图片内容嗅探 MIME,而非仅信任传入类型;只允许已知栅格格式并限制总大小。
total := 0
for i, image := range input.Images {
total += len(image.Data)
if total > CanvasImageBytesLimit || len(image.Data) == 0 || http.DetectContentType(image.Data) != image.MIME {
fail(w, 400, "invalid_ai_request")
return
}
extension := map[string]string{"image/png": "png", "image/jpeg": "jpeg", "image/webp": "webp", "image/gif": "gif"}[image.MIME]
if extension == "" {
fail(w, 400, "invalid_ai_request")
return
}
path := filepath.Join(job, fmt.Sprintf("input-%d.%s", i, extension))
if os.WriteFile(path, image.Data, 0600) != nil {
fail(w, 503, "codex_unavailable")
return
}
args = append(args, "--image", path)
}
args = append(args, "-")
prompt := input.Prompt
if imageOutput {
prompt = "Use the built-in image_generation tool to generate exactly one raster image following the supplied canvas instruction. Do not use shell, SVG, external URLs or substitute a textual description. Return a brief confirmation after generating the image.\n" + prompt
}
if len(prompt) > CanvasInputLimit {
fail(w, 413, "context_too_large")
return
}
cmd := exec.CommandContext(ctx, executable, args...)
cmd.Dir = "/work"
cmd.Env = []string{"PATH=/usr/local/bin:/usr/bin:/bin", "HOME=/home/node", "CODEX_HOME=" + home, "SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt"}
cmd.Stdin = strings.NewReader(prompt)
// 独立进程组使请求取消/超时可杀掉 CLI 及其子进程,避免残留后台任务。
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.Cancel = func() error {
err := syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
if errors.Is(err, syscall.ESRCH) {
return os.ErrProcessDone
}
return err
}
cmd.WaitDelay = 2 * time.Second
output := outputBuffer{limit: 2 << 20}
cmd.Stdout = &output
if err = cmd.Run(); err != nil {
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
fail(w, 504, "codex_timeout")
} else {
fail(w, 502, "generation_failed")
}
return
}
if output.exceeded {
fail(w, 502, "generation_failed")
return
}
// CLI 退出零还不够:事件流必须完成且无错误,图片结果还需从专用产物目录读取。
text, completed := canvasAgentText(output.buffer.Bytes())
if !completed {
fail(w, 502, "generation_failed")
return
}
result := CanvasOutput{Kind: "text", Text: text}
if imageOutput {
image, err := readCanvasGeneratedImage(filepath.Join(home, "generated_images"))
if err != nil {
fail(w, 502, "generation_failed")
return
}
result = CanvasOutput{Kind: "image", Image: image}
} else if len(text) > maxOutput {
fail(w, 502, "generation_failed")
return
}
writeJSON(w, 200, map[string]any{"output": result})
}
// canvasAgentText 逐行读取 JSON 事件,保留最后一条 agent_message;任何坏行或失败事件均拒绝。
func canvasAgentText(raw []byte) (string, bool) {
result := ""
completed := false
for _, line := range bytes.Split(bytes.TrimSpace(raw), []byte("\n")) {
var event struct {
Type string `json:"type"`
Item struct {
Type string `json:"type"`
Text string `json:"text"`
} `json:"item"`
}
if json.Unmarshal(line, &event) != nil {
return "", false
}
if event.Type == "turn.failed" || event.Type == "error" {
return "", false
}
if event.Type == "item.completed" && event.Item.Type == "agent_message" {
result = event.Item.Text
}
if event.Type == "turn.completed" {
completed = true
}
}
return result, completed
}
// readCanvasGeneratedImage 只遍历本次 generated_images,拒绝软链接、非常规文件和多张候选图片。
// 此处只做格式嗅探与字节限制;完整解码和尺寸验证由平台资产接收流程负责。
func readCanvasGeneratedImage(root string) (*CanvasImage, error) {
var result *CanvasImage
err := filepath.WalkDir(root, func(path string, entry fs.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
if entry.Type()&os.ModeSymlink != 0 {
return errors.New("invalid_artifact")
}
if entry.IsDir() {
return nil
}
info, err := entry.Info()
if err != nil {
return err
}
if !info.Mode().IsRegular() {
return errors.New("invalid_artifact")
}
ext := strings.ToLower(filepath.Ext(path))
if ext != ".png" && ext != ".jpeg" && ext != ".jpg" && ext != ".webp" && ext != ".gif" {
return nil
}
if result != nil || info.Size() <= 0 || info.Size() > CanvasImageBytesLimit {
return errors.New("invalid_artifact")
}
data, err := os.ReadFile(path)
if err != nil {
return err
}
mime := http.DetectContentType(data)
switch mime {
case "image/png", "image/jpeg", "image/webp", "image/gif":
default:
return errors.New("invalid_artifact")
}
result = &CanvasImage{MIME: mime, Data: data}
return nil
})
if err != nil {
return nil, err
}
if result == nil {
return nil, errors.New("image_missing")
}
return result, nil
}
-153
View File
@@ -1,153 +0,0 @@
// 公开文本生成代理:用项目专属凭据授权后,把受限任务通过 Unix IPC 转发给 worker。
package codex
import (
"bytes"
"context"
"crypto/sha256"
"crypto/subtle"
"encoding/hex"
"encoding/json"
"errors"
"io"
"net"
"net/http"
"os"
"strings"
"time"
)
// 公开请求 32 KiB、返回 512 KiB;worker 执行期限九十秒,IPC 客户端另留两秒收尾。
const (
maxRequest = 32 << 10
maxOutput = 512 << 10
timeout = 90 * time.Second
)
// task 仅允许 prompt,公开调用方不能传 sandbox、工具配置或可执行参数。
type task struct {
Prompt string `json:"prompt"`
}
// writeJSON 统一输出 JSON 并禁用缓存,内部调用者须在此之前完成状态码选择。
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}
// fail 将依赖或授权失败转换为稳定错误码,避免向公开 API 泄露本地路径和配置。
func fail(w http.ResponseWriter, status int, code string) {
writeJSON(w, status, map[string]string{"error": code})
}
// readTask 限制 JSON 大小、未知字段、尾随值与空白 prompt;失败时已写响应。
func readTask(w http.ResponseWriter, r *http.Request, limit int64) (task, bool) {
var input task
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, limit))
decoder.DisallowUnknownFields()
err := decoder.Decode(&input)
if err == nil {
err = decoder.Decode(new(any))
if err == io.EOF && strings.TrimSpace(input.Prompt) != "" {
return input, true
}
}
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
fail(w, 413, "request_too_large")
} else {
fail(w, 400, "invalid_task")
}
return task{}, false
}
// Register enables the public endpoint only when both configuration files are supplied.
// Each credential digest belongs to exactly one project.
// Register 在两项配置齐备时挂载路由,凭据文件每次请求重新读取以支持撤销。
func Register(mux *http.ServeMux, projects map[string]string, socket, grantsFile string) error {
if socket == "" && grantsFile == "" {
return nil
}
if socket == "" || grantsFile == "" {
return errors.New("Codex requires both a socket and a grants file")
}
transport := &http.Transport{
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
return (&net.Dialer{}).DialContext(ctx, "unix", socket)
},
DisableKeepAlives: true,
}
client := &http.Client{
Transport: transport,
Timeout: timeout + 2*time.Second,
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
}
mux.HandleFunc("POST /projects/{project}/codex/exec", func(w http.ResponseWriter, r *http.Request) {
scheme, token, _ := strings.Cut(r.Header.Get("Authorization"), " ")
key, err := hex.DecodeString(token)
if !strings.EqualFold(scheme, "Bearer") || err != nil || len(key) != 32 {
w.Header().Set("WWW-Authenticate", "Bearer")
fail(w, 401, "unauthorized")
return
}
data, err := os.ReadFile(grantsFile)
var grants map[string]string
if err != nil || json.Unmarshal(data, &grants) != nil {
fail(w, 503, "codex_unavailable")
return
}
// 凭据是 32 字节十六进制值;将摘要与授权表恒定时间比较,再核对目标项目作用域。
hash := sha256.Sum256(key)
var scope string
for digest, project := range grants {
value, err := hex.DecodeString(digest)
if err == nil && subtle.ConstantTimeCompare(hash[:], value) == 1 {
scope = project
}
}
if scope == "" {
w.Header().Set("WWW-Authenticate", "Bearer")
fail(w, 401, "unauthorized")
return
}
project := r.PathValue("project")
if _, exists := projects[project]; !exists || scope != project {
fail(w, 403, "forbidden")
return
}
input, ok := readTask(w, r, maxRequest)
if !ok {
return
}
// IPC 只发送解析后的任务体,不转发公开 Authorization 头;连接目的地固定为配置的 socket。
body, _ := json.Marshal(input)
req, err := http.NewRequestWithContext(r.Context(), http.MethodPost, "http://codex/exec", bytes.NewReader(body))
if err != nil {
fail(w, 502, "codex_unavailable")
return
}
resp, err := client.Do(req)
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
fail(w, 504, "codex_timeout")
} else {
fail(w, 502, "codex_unavailable")
}
return
}
defer resp.Body.Close()
// worker 响应必须在预算内且为合法 JSON;保留其状态与 Retry-After,隐藏传输错误细节。
data, err = io.ReadAll(io.LimitReader(resp.Body, maxOutput+1))
if err != nil || len(data) > maxOutput || !json.Valid(data) {
fail(w, 502, "invalid_codex_response")
return
}
if retry := resp.Header.Get("Retry-After"); retry != "" {
w.Header().Set("Retry-After", retry)
}
writeJSON(w, resp.StatusCode, json.RawMessage(data))
})
return nil
}
-72
View File
@@ -1,72 +0,0 @@
// 公开代理回归使用临时 Unix socket 假 worker,不访问外部服务或真实 CLI。
package codex
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
)
// TestProjectAuthorizationAndForwarding 检查缺凭据/跨项目拒绝、严格任务体、大小限制及授权文件即时撤销。
func TestProjectAuthorizationAndForwarding(t *testing.T) {
dir := t.TempDir()
socket := filepath.Join(dir, "worker.sock")
listener, err := net.Listen("unix", socket)
if err != nil {
t.Fatal(err)
}
// 假 worker 要求代理已移除 Authorization,只回显 prompt,用于确认最小化转发契约。
worker := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/exec" || r.Header.Get("Authorization") != "" {
fail(w, 500, "unexpected_worker_request")
return
}
input, ok := readTask(w, r, 6*maxRequest)
if ok {
writeJSON(w, 200, map[string]string{"result": input.Prompt})
}
})}
go worker.Serve(listener)
t.Cleanup(func() { _ = worker.Close() })
key := make([]byte, 32)
token := hex.EncodeToString(key)
grants := filepath.Join(dir, "grants.json")
writeGrants := func(data string) {
t.Helper()
if err := os.WriteFile(grants, []byte(data), 0600); err != nil {
t.Fatal(err)
}
}
writeGrants(fmt.Sprintf(`{"%x":"notes"}`, sha256.Sum256(key)))
mux := http.NewServeMux()
if err := Register(mux, map[string]string{"notes": "", "board": ""}, socket, grants); err != nil {
t.Fatal(err)
}
check := func(project, credential, body string, status int, response string) {
t.Helper()
r := httptest.NewRequest("POST", "/projects/"+project+"/codex/exec", strings.NewReader(body))
if credential != "" {
r.Header.Set("Authorization", "Bearer "+credential)
}
w := httptest.NewRecorder()
mux.ServeHTTP(w, r)
if w.Code != status || !strings.Contains(w.Body.String(), response) {
t.Fatalf("got %d %s, want %d containing %q", w.Code, w.Body.String(), status, response)
}
}
check("notes", "", `{"prompt":"hello"}`, 401, "unauthorized")
check("board", token, `{"prompt":"hello"}`, 403, "forbidden")
check("notes", token, `{"prompt":"hello","sandbox":"danger"}`, 400, "invalid_task")
check("notes", token, `{"prompt":"`+strings.Repeat("x", maxRequest)+`"}`, 413, "request_too_large")
check("notes", token, `{"prompt":"hello"}`, 200, `"result":"hello"`)
writeGrants("{}")
check("notes", token, `{"prompt":"hello"}`, 401, "unauthorized")
}
-197
View File
@@ -1,197 +0,0 @@
// Package codex 在核心 API 与受限 CLI worker 间通过 Unix socket 通信,隔离公开凭据与本地执行环境。
package codex
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net"
"net/http"
"os"
"os/exec"
"strings"
"syscall"
"time"
)
// executable 指向部署容器预装 CLI,不从请求或 PATH 选择可执行文件。
const executable = "/opt/codex/node_modules/.bin/codex"
var errOutputLimit = errors.New("Codex output limit exceeded")
// outputBuffer 对 CLI stdout 累计限额;超限标记用于进程结束后选择稳定错误响应。
type outputBuffer struct {
buffer bytes.Buffer
exceeded bool
limit int
}
// Write 实现 io.Writer,默认使用公共输出限制,画布事件流可另设更大内部预算。
func (b *outputBuffer) Write(p []byte) (int, error) {
limit := b.limit
if limit == 0 {
limit = maxOutput
}
if len(p) > limit-b.buffer.Len() {
b.exceeded = true
return 0, errOutputLimit
}
return b.buffer.Write(p)
}
// ServeWorker 由 main 的 codex-worker 模式调用,重建 0600 socket,只允许一个生成任务同时执行。
func ServeWorker(socket string) error {
syscall.Umask(0077)
if err := os.Remove(socket); err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
listener, err := net.Listen("unix", socket)
if err != nil {
return err
}
defer listener.Close()
if err := os.Chmod(socket, 0600); err != nil {
return err
}
// 文本 /exec 与 /canvas/exec 共享一个槽位;忙时立即 429,目录读取不占执行槽。
slot := make(chan struct{}, 1)
mux := http.NewServeMux()
mux.HandleFunc("POST /exec", func(w http.ResponseWriter, r *http.Request) {
select {
case slot <- struct{}{}:
defer func() { <-slot }()
default:
w.Header().Set("Retry-After", "5")
fail(w, 429, "codex_busy")
return
}
input, ok := readTask(w, r, 6*maxRequest)
if ok {
execute(w, r, input.Prompt)
}
})
mux.HandleFunc("GET /canvas/models", func(w http.ResponseWriter, r *http.Request) {
models, err := workerCanvasModels()
if err != nil {
fail(w, 503, "codex_unavailable")
return
}
writeJSON(w, 200, map[string]any{"models": models})
})
mux.HandleFunc("POST /canvas/exec", func(w http.ResponseWriter, r *http.Request) {
var input CanvasTask
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, canvasArtifactResponseLimit+CanvasInputLimit))
decoder.DisallowUnknownFields()
if decoder.Decode(&input) != nil || decoder.Decode(new(any)) != io.EOF || len(input.Prompt) > CanvasInputLimit || strings.TrimSpace(input.Prompt) == "" || len(input.Parameters) > 0 || len(input.Images) > 4 {
fail(w, 400, "invalid_ai_request")
return
}
models, err := workerCanvasModels()
if err != nil {
fail(w, 503, "codex_unavailable")
return
}
// 仅按公开 ID 匹配当前目录,再在 worker 内取 Backend,调用方不能任意指定 CLI 模型名。
var selected *CanvasModel
for _, model := range models {
if model.ID == input.ModelID {
copy := model
selected = &copy
}
}
if selected == nil {
fail(w, 422, "model_unavailable")
return
}
select {
case slot <- struct{}{}:
defer func() { <-slot }()
default:
w.Header().Set("Retry-After", "5")
fail(w, 429, "codex_busy")
return
}
executeCanvasTask(w, r, input, *selected)
})
server := &http.Server{Handler: mux, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 195 * time.Second}
return server.Serve(listener)
}
// execute 为旧文本入口保留默认模型选择,实际进程生命周期集中在 executeModel。
func execute(w http.ResponseWriter, r *http.Request, prompt string) { executeModel(w, r, prompt, "") }
// executeModel 用请求期限约束 CLI,禁用外部工具能力;失败仅公开错误码,不转发 stderr。
func executeModel(w http.ResponseWriter, r *http.Request, prompt, model string) {
ctx, cancel := context.WithTimeout(r.Context(), timeout)
defer cancel()
cmd := exec.CommandContext(ctx, executable, "--ask-for-approval", "never",
"--disable", "shell_tool", "--disable", "apps", "--disable", "plugins",
"--disable", "multi_agent", "--disable", "hooks", "--disable", "memories",
"-c", `web_search="disabled"`, "exec", "--json", "--sandbox", "read-only", "--skip-git-repo-check", "--ephemeral", "-")
if model != "" {
cmd.Args = append(cmd.Args[:len(cmd.Args)-1], "--model", model, "-")
}
cmd.Dir = "/work"
cmd.Env = []string{"PATH=/usr/local/bin:/usr/bin:/bin", "HOME=/home/node", "CODEX_HOME=/home/node/.codex", "SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt"}
cmd.Stdin = strings.NewReader(prompt)
// Setpgid 配合负 PID kill 终止整个进程组;WaitDelay 约束取消后的输出管道等待。
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
cmd.Cancel = func() error {
err := syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
if errors.Is(err, syscall.ESRCH) {
return os.ErrProcessDone
}
return err
}
cmd.WaitDelay = 2 * time.Second
var output outputBuffer
cmd.Stdout, cmd.Stderr = &output, io.Discard
err := cmd.Run()
switch {
case output.exceeded:
fail(w, 502, "codex_output_too_large")
case errors.Is(ctx.Err(), context.DeadlineExceeded):
fail(w, 504, "codex_timeout")
case err != nil:
fail(w, 502, "codex_failed")
default:
// 只有合法事件流、成功结束事件及非空最终文本才能作为公开生成结果返回。
var result string
var completed bool
for _, line := range bytes.Split(bytes.TrimSpace(output.buffer.Bytes()), []byte("\n")) {
var event struct {
Type string `json:"type"`
Item struct {
Type string `json:"type"`
Text string `json:"text"`
} `json:"item"`
}
if json.Unmarshal(line, &event) != nil {
fail(w, 502, "invalid_codex_response")
return
}
if event.Type == "item.completed" && event.Item.Type == "agent_message" {
result = event.Item.Text
}
if event.Type == "turn.failed" || event.Type == "error" {
fail(w, 502, "codex_failed")
return
}
if event.Type == "turn.completed" {
completed = true
}
}
if !completed || result == "" {
fail(w, 502, "codex_failed")
return
}
response, _ := json.Marshal(map[string]string{"result": result})
if len(response) >= maxOutput {
fail(w, 502, "codex_output_too_large")
return
}
writeJSON(w, 200, json.RawMessage(response))
}
}
-262
View File
@@ -1,262 +0,0 @@
// 预览派生与进程内缓存:只缓存不可变图片字节,权限必须由调用方每次读取前另行检查。
package platform
import (
"bytes"
"container/list"
"context"
"crypto/sha256"
"encoding/binary"
"errors"
"fmt"
"image"
"image/color"
"image/jpeg"
"image/png"
"sync"
"golang.org/x/image/draw"
)
// assetPreviewResult 只包含编码字节和 MIME,可与原图共用只读切片,禁止调用者原地修改。
type assetPreviewResult struct {
data []byte
mime string
}
// assetPreviewEntry 存储在 LRU 链表中,key 同时作为 map 索引,便于常数时间淘汰。
type assetPreviewEntry struct {
key string
value assetPreviewResult
}
// 缓存最多保留 32 MiB/128 项编码结果,互斥锁只覆盖索引操作,不覆盖解码缩放。
var previewMemory = struct {
sync.Mutex
entries map[string]*list.Element
order *list.List
bytes int
}{entries: make(map[string]*list.Element), order: list.New()}
// previewSlots 将所有预览完整解码限制为单并发,避免多个大图同时分配像素内存。
var previewSlots = make(chan struct{}, 1)
// previewWidth 仅接受原图或固定 1024 预览,不允许任意宽度组合造成无界缓存键。
func previewWidth(variant, width string) (int, error) {
if variant == "" && width == "" {
return 0, nil
}
if variant == "preview" && (width == "" || width == "1024") {
return 1024, nil
}
return 0, errors.New("invalid_asset_variant")
}
// Cache only immutable bytes, after the caller checks current asset permission.
// Bound both decoded concurrency and retained encoded data.
// cachedAssetPreview 用原图摘要与宽度做键,命中即提升 LRU;等待执行槽可随请求取消。
func cachedAssetPreview(ctx context.Context, encoded []byte, mime string, width int) (assetPreviewResult, error) {
key := fmt.Sprintf("%x:%d", sha256.Sum256(encoded), width)
previewMemory.Lock()
if entry := previewMemory.entries[key]; entry != nil {
previewMemory.order.MoveToFront(entry)
result := entry.Value.(assetPreviewEntry).value
previewMemory.Unlock()
return result, nil
}
previewMemory.Unlock()
select {
case previewSlots <- struct{}{}:
case <-ctx.Done():
return assetPreviewResult{}, ctx.Err()
}
defer func() { <-previewSlots }()
// Another request may have finished this same preview while we waited.
previewMemory.Lock()
if entry := previewMemory.entries[key]; entry != nil {
result := entry.Value.(assetPreviewEntry).value
previewMemory.order.MoveToFront(entry)
previewMemory.Unlock()
return result, nil
}
previewMemory.Unlock()
result, err := makeAssetPreview(encoded, mime, width)
if err != nil {
return result, err
}
// 单项过大仍可响应,但不留在缓存;其余按字节和项数双预算淘汰末尾最久未用项。
if len(result.data) > 8<<20 {
return result, nil
}
previewMemory.Lock()
defer previewMemory.Unlock()
for previewMemory.bytes+len(result.data) > 32<<20 || previewMemory.order.Len() >= 128 {
tail := previewMemory.order.Back()
if tail == nil {
break
}
old := tail.Value.(assetPreviewEntry)
previewMemory.bytes -= len(old.value.data)
delete(previewMemory.entries, old.key)
previewMemory.order.Remove(tail)
}
previewMemory.entries[key] = previewMemory.order.PushFront(assetPreviewEntry{key, result})
previewMemory.bytes += len(result.data)
return result, nil
}
// makeAssetPreview 保留 GIF 动画和足够小的原图,其余应用 EXIF 后等比例缩至最长边预算。
func makeAssetPreview(encoded []byte, mime string, width int) (assetPreviewResult, error) {
original := assetPreviewResult{encoded, mime}
// Keep animation intact. Original bytes remain the canonical AI/download input.
if mime == "image/gif" {
return original, nil
}
config, _, err := image.DecodeConfig(bytes.NewReader(encoded))
if err != nil {
return original, err
}
if config.Width <= 0 || config.Height <= 0 || int64(config.Width)*int64(config.Height) > assetPixelLimit {
return original, errors.New("invalid_image_dimensions")
}
if config.Width <= width && config.Height <= width && len(encoded) <= 64<<10 {
return original, nil
}
source, _, err := image.Decode(bytes.NewReader(encoded))
if err != nil {
return original, err
}
orientation := jpegOrientation(encoded)
if orientation != 1 {
source = orientedAsset{source, orientation}
}
bounds := source.Bounds()
w, h := bounds.Dx(), bounds.Dy()
if w > width || h > width {
if w >= h {
h = max(1, h*width/w)
w = width
} else {
w = max(1, w*width/h)
h = width
}
}
resized := image.NewNRGBA(image.Rect(0, 0, w, h))
draw.CatmullRom.Scale(resized, resized.Bounds(), source, source.Bounds(), draw.Src, nil)
var output bytes.Buffer
outputMime := "image/png"
// 不透明预览编码 JPEG 以减体积,透明预览保留 PNG;原图字节始终不被覆盖。
if resized.Opaque() {
err = jpeg.Encode(&output, resized, &jpeg.Options{Quality: 82})
outputMime = "image/jpeg"
} else {
err = png.Encode(&output, resized)
}
if err != nil {
return original, err
}
// 无需修正方向且重编码没有变小时直接用原图,避免更大派生文件。
if output.Len() >= len(encoded) && orientation == 1 {
return original, nil
}
return assetPreviewResult{output.Bytes(), outputMime}, nil
}
// JPEG EXIF orientation is applied to previews instead of silently rotating a
// phone photograph after its EXIF metadata is removed by the image encoder.
// jpegOrientation 仅解析 JPEG APP1 中 TIFF 的 Orientation,逐层检查长度,异常/缺省均返回正常方向一。
func jpegOrientation(data []byte) int {
if len(data) < 4 || data[0] != 0xff || data[1] != 0xd8 {
return 1
}
for at := 2; at+4 <= len(data); {
if data[at] != 0xff {
return 1
}
marker := data[at+1]
if marker == 0xda || marker == 0xd9 {
return 1
}
length := int(binary.BigEndian.Uint16(data[at+2 : at+4]))
if length < 2 || at+2+length > len(data) {
return 1
}
part := data[at+4 : at+2+length]
if marker == 0xe1 && len(part) >= 14 && string(part[:6]) == "Exif\x00\x00" {
tiff := part[6:]
var order binary.ByteOrder
switch string(tiff[:2]) {
case "II":
order = binary.LittleEndian
case "MM":
order = binary.BigEndian
default:
return 1
}
if order.Uint16(tiff[2:4]) != 42 {
return 1
}
offset := int(order.Uint32(tiff[4:8]))
if offset < 8 || offset+2 > len(tiff) {
return 1
}
count := int(order.Uint16(tiff[offset : offset+2]))
for i := 0; i < count; i++ {
entry := offset + 2 + i*12
if entry+12 > len(tiff) {
return 1
}
if order.Uint16(tiff[entry:entry+2]) == 0x112 && order.Uint16(tiff[entry+2:entry+4]) == 3 && order.Uint32(tiff[entry+4:entry+8]) == 1 {
value := int(order.Uint16(tiff[entry+8 : entry+10]))
if value >= 1 && value <= 8 {
return value
}
return 1
}
}
}
at += 2 + length
}
return 1
}
// orientedAsset 是只读坐标适配视图,不复制像素;5–8 方向旋转后宽高交换。
type orientedAsset struct {
image.Image
orientation int
}
// Bounds 报告纠正方向后的零起点矩形,供缩放器计算目标比例。
func (im orientedAsset) Bounds() image.Rectangle {
b := im.Image.Bounds()
if im.orientation >= 5 {
return image.Rect(0, 0, b.Dy(), b.Dx())
}
return image.Rect(0, 0, b.Dx(), b.Dy())
}
// ColorModel 继承原图颜色模型,实际像素读取交由 At 做反向坐标映射。
func (im orientedAsset) ColorModel() color.Model { return im.Image.ColorModel() }
// At 将显示坐标映回原图,再补 Bounds.Min,覆盖 EXIF 八种旋转/镜像组合。
func (im orientedAsset) At(x, y int) color.Color {
b := im.Image.Bounds()
w, h := b.Dx(), b.Dy()
switch im.orientation {
case 2:
x = w - 1 - x
case 3:
x, y = w-1-x, h-1-y
case 4:
y = h - 1 - y
case 5:
x, y = y, x
case 6:
x, y = y, h-1-x
case 7:
x, y = w-1-y, h-1-x
case 8:
x, y = w-1-y, x
}
return im.Image.At(b.Min.X+x, b.Min.Y+y)
}
-147
View File
@@ -1,147 +0,0 @@
// 画布与资产纯函数回归;测试说明对应实际断言,不依赖浏览器或真实模型。
package platform
import (
"bytes"
"context"
"encoding/binary"
"image"
"image/color"
"image/jpeg"
"image/png"
"testing"
)
// TestAssetPreviewDownscalesWithoutChangingOriginal 生成 1600×900 不透明图,验证缩至 512×288、转 JPEG、体积变小且原图字节不变,并比对缓存结果。
func TestAssetPreviewDownscalesWithoutChangingOriginal(t *testing.T) {
source := image.NewNRGBA(image.Rect(0, 0, 1600, 900))
for y := 0; y < 900; y++ {
for x := 0; x < 1600; x++ {
source.SetNRGBA(x, y, color.NRGBA{uint8(x), uint8(y), uint8(x * y), 255})
}
}
var encoded bytes.Buffer
if err := png.Encode(&encoded, source); err != nil {
t.Fatal(err)
}
original := append([]byte(nil), encoded.Bytes()...)
preview, err := makeAssetPreview(encoded.Bytes(), "image/png", 512)
if err != nil {
t.Fatal(err)
}
config, format, err := image.DecodeConfig(bytes.NewReader(preview.data))
if err != nil || config.Width != 512 || config.Height != 288 || format != "jpeg" {
t.Fatalf("bad preview %s %dx%d %v", format, config.Width, config.Height, err)
}
if len(preview.data) >= len(original) || !bytes.Equal(original, encoded.Bytes()) {
t.Fatal("preview must shrink without changing original")
}
cached, err := cachedAssetPreview(context.Background(), original, "image/png", 512)
if err != nil || !bytes.Equal(cached.data, preview.data) {
t.Fatal("cache result mismatch")
}
}
// TestAssetPreviewPreservesTransparencyAndAnimation 验证透明图继续用 PNG,GIF 分支直接保留传入字节;该 GIF 样本不验证真实动画解码。
func TestAssetPreviewPreservesTransparencyAndAnimation(t *testing.T) {
source := image.NewNRGBA(image.Rect(0, 0, 800, 400))
source.SetNRGBA(1, 1, color.NRGBA{255, 0, 0, 255})
var encoded bytes.Buffer
_ = png.Encode(&encoded, source)
preview, err := makeAssetPreview(encoded.Bytes(), "image/png", 256)
if err != nil {
t.Fatal(err)
}
decoded, format, err := image.Decode(bytes.NewReader(preview.data))
if err != nil || format != "png" {
t.Fatal("transparent image must stay PNG")
}
_, _, _, alpha := decoded.At(200, 100).RGBA()
if alpha != 0 {
t.Fatal("transparent background was lost")
}
original := []byte("GIF original animation bytes")
gif, err := makeAssetPreview(original, "image/gif", 512)
if err != nil || !bytes.Equal(gif.data, original) {
t.Fatal("GIF animation changed")
}
}
// TestAssetPreviewRejectsUnboundedWidths 验证公开参数仅接受原图或 1024 预览,拒绝任意宽度/未知变体;额外检查坏图片拒绝。
func TestAssetPreviewRejectsUnboundedWidths(t *testing.T) {
for _, value := range []string{"0", "1", "256", "512", "2048", "999999", "-1", "abc"} {
if _, err := previewWidth("preview", value); err == nil {
t.Errorf("accepted width %s", value)
}
}
for _, value := range []string{"", "1024"} {
if _, err := previewWidth("preview", value); err != nil {
t.Fatal(err)
}
}
if n, err := previewWidth("", ""); err != nil || n != 0 {
t.Fatal("original request changed")
}
if _, err := previewWidth("other", ""); err == nil {
t.Fatal("unknown variant accepted")
}
if _, err := makeAssetPreview([]byte("invalid"), "image/png", 512); err == nil {
t.Fatal("malformed image accepted")
}
}
// TestAssetPreviewAppliesJPEGOrientation 手工插入小端 EXIF 方向六,验证缩图前旋转使最终尺寸由横向变为 128×256。
func TestAssetPreviewAppliesJPEGOrientation(t *testing.T) {
source := image.NewNRGBA(image.Rect(0, 0, 800, 400))
for y := 0; y < 400; y++ {
for x := 0; x < 800; x++ {
source.SetNRGBA(x, y, color.NRGBA{255, 0, 0, 255})
}
}
var original bytes.Buffer
_ = jpeg.Encode(&original, source, nil)
tiff := make([]byte, 26)
copy(tiff, "II")
binary.LittleEndian.PutUint16(tiff[2:], 42)
binary.LittleEndian.PutUint32(tiff[4:], 8)
binary.LittleEndian.PutUint16(tiff[8:], 1)
binary.LittleEndian.PutUint16(tiff[10:], 0x112)
binary.LittleEndian.PutUint16(tiff[12:], 3)
binary.LittleEndian.PutUint32(tiff[14:], 1)
binary.LittleEndian.PutUint16(tiff[18:], 6)
exif := append([]byte("Exif\x00\x00"), tiff...)
segment := append([]byte{0xff, 0xe1, 0, byte(len(exif) + 2)}, exif...)
encoded := append(append(append([]byte{}, original.Bytes()[:2]...), segment...), original.Bytes()[2:]...)
if jpegOrientation(encoded) != 6 {
t.Fatal("EXIF orientation not decoded")
}
preview, err := makeAssetPreview(encoded, "image/jpeg", 256)
if err != nil {
t.Fatal(err)
}
config, _, err := image.DecodeConfig(bytes.NewReader(preview.data))
if err != nil || config.Width != 128 || config.Height != 256 {
t.Fatalf("rotated dimensions %dx%d %v", config.Width, config.Height, err)
}
}
// TestAllAssetOrientationMappings 在八个方向视图中遍历像素,检查唯一红像素不丢失或重复;不逐点断言每种方向的完整布局。
func TestAllAssetOrientationMappings(t *testing.T) {
source := image.NewNRGBA(image.Rect(0, 0, 3, 2))
source.SetNRGBA(0, 0, color.NRGBA{255, 0, 0, 255})
for orientation := 1; orientation <= 8; orientation++ {
oriented := orientedAsset{source, orientation}
red := 0
for y := 0; y < oriented.Bounds().Dy(); y++ {
for x := 0; x < oriented.Bounds().Dx(); x++ {
r, _, _, _ := oriented.At(x, y).RGBA()
if r > 0 {
red++
}
}
}
if red != 1 {
t.Errorf("orientation %d loses/repeats pixels", orientation)
}
}
}
-463
View File
@@ -1,463 +0,0 @@
// 不可变画布图片资产:上传原图字节并保留身份,读取时按当前绑定画布权限决定可见性。
package platform
import (
"bytes"
"crypto/sha256"
"database/sql"
"encoding/hex"
"encoding/json"
"errors"
"image"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"io"
"net/http"
"net/url"
"strconv"
"strings"
_ "golang.org/x/image/webp"
)
// assetLimit 是单图编码字节上限,assetPixelLimit 在完整解码前限制像素分配预算。
const assetLimit = 20 << 20
const assetPixelLimit = 40_000_000
// assetInfo 是公开元数据,URL 稳定引用私有原图路由,不包含图片内容或上传者身份。
type assetInfo struct {
ID string `json:"id"`
MIME string `json:"mime_type"`
Bytes int `json:"bytes"`
Width int `json:"width"`
Height int `json:"height"`
URL string `json:"url"`
}
// assetURL 将项目与工作区按路径段转义,所有绑定校验使用同一 URL 生成规则。
func (s *service) assetURL(project, workspace, id string) string {
return s.origin + "/projects/" + url.PathEscape(project) + "/workspaces/" + url.PathEscape(workspace) + "/assets/" + id
}
// Decode headers first and bound allocation before decoding the actual image.
// The MIME comes from the decoder, never from the filename or upload header.
// inspectAsset 先读取尺寸预算再完整解码,并比较两次识别格式/尺寸,拒绝截断或伪造头部图片。
func inspectAsset(encoded []byte) (string, int, int, error) {
config, format, err := image.DecodeConfig(bytes.NewReader(encoded))
if err != nil {
return "", 0, 0, err
}
if !canvasChoice(format, "png", "jpeg", "gif", "webp") || config.Width <= 0 || config.Height <= 0 || config.Width > assetPixelLimit || config.Height > assetPixelLimit || int64(config.Width)*int64(config.Height) > assetPixelLimit {
return "", 0, 0, errors.New("invalid_image_dimensions")
}
decoded, actual, err := image.Decode(bytes.NewReader(encoded))
if err != nil {
return "", 0, 0, err
}
if actual != format || decoded.Bounds().Dx() != config.Width || decoded.Bounds().Dy() != config.Height {
return "", 0, 0, errors.New("invalid_image")
}
return "image/" + format, config.Width, config.Height, nil
}
// uploadAsset 分两次事务检查编辑权限:接收慢 multipart 正文和解码时不持有工作区锁。
// 幂等键限定在上传者/工作区,重复请求必须保持相同图片摘要和可选资源 ID。
func (s *service) uploadAsset(w http.ResponseWriter, r *http.Request, project, account string) error {
if r.Method != http.MethodPost {
reject(w, 405, "method_not_allowed")
return nil
}
key := canvasIdempotencyKey(r)
if !uuidSlugPattern.MatchString(key) {
reject(w, 400, "invalid_idempotency_key")
return nil
}
resourceID := strings.ToLower(r.Header.Get("X-Resource-Id"))
if resourceID != "" && !uuidSlugPattern.MatchString(resourceID) {
reject(w, 400, "invalid_resource_id")
return nil
}
// 兼容旧版直接返回 assetInfo;指定 X-Resource-Id 的客户端获得带请求 ID 的 v2 应用回执。
respond := func(info assetInfo) {
if resourceID == "" {
reply(w, 201, info)
} else {
reply(w, 201, response{"protocol_version": 2, "request_id": key, "status": "applied", "asset": info})
}
}
tx, err := s.db.BeginTx(r.Context(), nil)
if err != nil {
return err
}
defer tx.Rollback()
workspace := r.PathValue("workspace")
_, role, err := lockWorkspace(r.Context(), tx, project, workspace, account)
if err != nil {
return err
}
if role == "viewer" {
reject(w, 403, "forbidden")
return nil
}
// Do not hold a workspace lock during a slow multipart upload. Recheck below.
if err = tx.Rollback(); err != nil {
return err
}
r.Body = http.MaxBytesReader(w, r.Body, assetLimit+(64<<10))
reader, err := r.MultipartReader()
if err != nil {
reject(w, 400, "invalid_asset")
return nil
}
var encoded []byte
count := 0
for {
part, e := reader.NextPart()
if e == io.EOF {
break
}
if e != nil {
reject(w, 413, "asset_too_large")
return nil
}
if part.FormName() != "image" && part.FormName() != "file" {
part.Close()
reject(w, 400, "invalid_asset")
return nil
}
count++
if count > 1 {
part.Close()
reject(w, 400, "invalid_asset")
return nil
}
encoded, e = io.ReadAll(io.LimitReader(part, assetLimit+1))
part.Close()
if e != nil || len(encoded) > assetLimit {
reject(w, 413, "asset_too_large")
return nil
}
}
if count != 1 || len(encoded) == 0 {
reject(w, 400, "invalid_asset")
return nil
}
mime, width, height, err := inspectAsset(encoded)
if err != nil {
reject(w, 400, "invalid_asset")
return nil
}
tx, err = s.db.BeginTx(r.Context(), nil)
if err != nil {
return err
}
defer tx.Rollback()
_, role, err = lockWorkspace(r.Context(), tx, project, workspace, account)
if err != nil {
return err
}
if role == "viewer" {
reject(w, 403, "forbidden")
return nil
}
// 第二次取锁后重读权限和幂等记录,防止上传期间撤权或并发重试产生重复资产。
digest := sha256.Sum256(encoded)
hash := hex.EncodeToString(digest[:])
info := assetInfo{MIME: mime, Bytes: len(encoded), Width: width, Height: height}
var previous string
err = tx.QueryRowContext(r.Context(), `SELECT id::text,digest FROM canvas_assets WHERE project=$1 AND workspace_id=$2 AND uploaded_by=$3 AND idempotency_key=$4`, project, workspace, account, key).Scan(&info.ID, &previous)
if err == nil {
if previous != hash || resourceID != "" && resourceID != info.ID {
reject(w, 409, "idempotency_conflict")
return nil
}
info.URL = s.assetURL(project, workspace, info.ID)
respond(info)
return nil
}
if err != sql.ErrNoRows {
return err
}
if resourceID != "" {
var occupied bool
if err = tx.QueryRowContext(r.Context(), `SELECT EXISTS(SELECT 1 FROM canvas_assets WHERE project=$1 AND workspace_id=$2 AND id=$3)`, project, workspace, resourceID).Scan(&occupied); err != nil {
return err
}
if occupied {
reject(w, 409, "resource_identity_conflict")
return nil
}
}
err = tx.QueryRowContext(r.Context(), `INSERT INTO canvas_assets(project,workspace_id,uploaded_by,mime_type,bytes,width,height,digest,idempotency_key,id) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,COALESCE(NULLIF($10,'')::uuid,gen_random_uuid())) RETURNING id::text`, project, workspace, account, mime, encoded, width, height, hash, key, resourceID).Scan(&info.ID)
if err != nil {
return err
}
if err = tx.Commit(); err != nil {
return err
}
info.URL = s.assetURL(project, workspace, info.ID)
respond(info)
return nil
}
// A missing receipt is unknown: callers may only retry the same resource/key/bytes.
// assetOperation 在当前成员授权下查找本人上传回执;缺记录为 unknown,不能据此换键重传或判定零写入。
func (s *service) assetOperation(w http.ResponseWriter, r *http.Request, project, account string) error {
if r.Method != http.MethodGet {
reject(w, 405, "method_not_allowed")
return nil
}
key, workspace := r.PathValue("request"), r.PathValue("workspace")
if !uuidSlugPattern.MatchString(key) {
reject(w, 400, "invalid_idempotency_key")
return nil
}
tx, err := s.db.BeginTx(r.Context(), nil)
if err != nil {
return err
}
defer tx.Rollback()
if _, _, err = lockWorkspace(r.Context(), tx, project, workspace, account); err != nil {
return err
}
var info assetInfo
err = tx.QueryRowContext(r.Context(), `SELECT id::text,mime_type,octet_length(bytes),width,height FROM canvas_assets WHERE project=$1 AND workspace_id=$2 AND uploaded_by=$3 AND idempotency_key=$4`, project, workspace, account, key).Scan(&info.ID, &info.MIME, &info.Bytes, &info.Width, &info.Height)
if err == sql.ErrNoRows {
reply(w, 404, response{"protocol_version": 2, "request_id": key, "status": "unknown", "error": "asset_receipt_unknown"})
return nil
}
if err != nil {
return err
}
info.URL = s.assetURL(project, workspace, info.ID)
reply(w, 200, response{"protocol_version": 2, "request_id": key, "status": "applied", "asset": info})
return nil
}
// assetReadable 依赖调用方持有工作区锁:无绑定时只允许上传者/admin,有绑定时需至少一个绑定画布可读。
// 绑定可读性复用 lockMaterial,因此继承根画布权限并尊重子图归档状态。
func assetReadable(r *http.Request, tx *sql.Tx, project, workspace, id, account string) (bool, error) {
var uploader string
err := tx.QueryRowContext(r.Context(), `SELECT uploaded_by::text FROM canvas_assets WHERE project=$1 AND workspace_id=$2 AND id=$3`, project, workspace, id).Scan(&uploader)
if err != nil {
return false, err
}
var bindings int
err = tx.QueryRowContext(r.Context(), `SELECT count(*) FROM canvas_asset_bindings WHERE project=$1 AND workspace_id=$2 AND asset_id=$3`, project, workspace, id).Scan(&bindings)
if err != nil {
return false, err
}
if bindings == 0 {
if uploader == account {
return true, nil
}
var admin bool
err = tx.QueryRowContext(r.Context(), `SELECT EXISTS(SELECT 1 FROM workspace_members WHERE project=$1 AND workspace_id=$2 AND account_id=$3 AND role='admin')`, project, workspace, account).Scan(&admin)
return admin, err
}
rows, err := tx.QueryContext(r.Context(), `SELECT board_id::text FROM canvas_asset_bindings WHERE project=$1 AND workspace_id=$2 AND asset_id=$3 ORDER BY board_id`, project, workspace, id)
if err != nil {
return false, err
}
boards := []string{}
for rows.Next() {
var board string
if err = rows.Scan(&board); err != nil {
rows.Close()
return false, err
}
boards = append(boards, board)
}
err = rows.Err()
rows.Close()
if err != nil {
return false, err
}
for _, board := range boards {
_, _, err := lockMaterial(r.Context(), tx, project, workspace, board, account)
if err == nil {
return true, nil
}
if err != sql.ErrNoRows {
return false, err
}
}
return false, nil
}
// Metadata uses the same read policy as original bytes; it is not a persistent grant.
// getAssetMetadata 每次重新鉴权,读取不可变身份摘要后先提交释放锁,再写 JSON,不发放持久权限。
func (s *service) getAssetMetadata(w http.ResponseWriter, r *http.Request, project, account string) error {
if r.Method != http.MethodGet {
reject(w, 405, "method_not_allowed")
return nil
}
id, workspace := r.PathValue("asset"), r.PathValue("workspace")
if !uuidSlugPattern.MatchString(id) {
reject(w, 404, "not_found")
return nil
}
tx, err := s.db.BeginTx(r.Context(), nil)
if err != nil {
return err
}
defer tx.Rollback()
var locked string
err = tx.QueryRowContext(r.Context(), `SELECT id::text FROM workspaces WHERE project=$1 AND id=$2 FOR UPDATE`, project, workspace).Scan(&locked)
if err != nil {
return err
}
allowed, err := assetReadable(r, tx, project, workspace, id, account)
if err != nil {
return err
}
if !allowed {
reject(w, 404, "not_found")
return nil
}
var info assetInfo
var digest string
err = tx.QueryRowContext(r.Context(), `SELECT id::text,mime_type,octet_length(bytes),width,height,digest FROM canvas_assets WHERE project=$1 AND workspace_id=$2 AND id=$3`, project, workspace, id).Scan(&info.ID, &info.MIME, &info.Bytes, &info.Width, &info.Height, &digest)
if err != nil {
return err
}
if err = tx.Commit(); err != nil {
return err
}
info.URL = s.assetURL(project, workspace, id)
w.Header().Set("Cache-Control", "private, no-store")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(response{"metadata_version": 1, "asset": info, "sha256": digest})
return nil
}
// getAsset 同时服务原图与固定预览变体;先一致读取权限/字节,释放事务后才缩图或写响应。
func (s *service) getAsset(w http.ResponseWriter, r *http.Request, project, account string) error {
if r.Method != http.MethodGet {
reject(w, 405, "method_not_allowed")
return nil
}
width, variantErr := previewWidth(r.URL.Query().Get("variant"), r.URL.Query().Get("width"))
if variantErr != nil {
reject(w, 400, "invalid_asset_variant")
return nil
}
id := r.PathValue("asset")
if !uuidSlugPattern.MatchString(id) {
reject(w, 404, "not_found")
return nil
}
workspace := r.PathValue("workspace")
tx, err := s.db.BeginTx(r.Context(), nil)
if err != nil {
return err
}
defer tx.Rollback()
// Serialize with permission and binding changes before making the read decision.
var locked string
err = tx.QueryRowContext(r.Context(), `SELECT id::text FROM workspaces WHERE project=$1 AND id=$2 FOR UPDATE`, project, workspace).Scan(&locked)
if err != nil {
return err
}
allowed, err := assetReadable(r, tx, project, workspace, id, account)
if err != nil {
return err
}
if !allowed {
reject(w, 404, "not_found")
return nil
}
var encoded []byte
var mime string
err = tx.QueryRowContext(r.Context(), `SELECT mime_type,bytes FROM canvas_assets WHERE project=$1 AND workspace_id=$2 AND id=$3`, project, workspace, id).Scan(&mime, &encoded)
if err != nil {
return err
}
// Permission and immutable bytes are now read consistently. Release locks
// before resizing or waiting for a slow public client to consume the body.
if err = tx.Rollback(); err != nil {
return err
}
variant := "original"
if width > 0 {
preview, e := cachedAssetPreview(r.Context(), encoded, mime, width)
if e != nil {
return e
}
encoded, mime = preview.data, preview.mime
variant = "preview"
}
w.Header().Set("X-Asset-Variant", variant)
w.Header().Set("Content-Type", mime)
w.Header().Set("Content-Length", strconv.Itoa(len(encoded)))
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Cache-Control", "private, no-store")
w.WriteHeader(200)
_, err = w.Write(encoded)
return err
}
// attachCanvasAssets 为文档内显式 assetId 或同工作区托管 URL 追加绑定;不删除旧绑定,调用方先验证权限。
func (s *service) attachCanvasAssets(r *http.Request, tx *sql.Tx, project, workspace, board string, raw json.RawMessage) error {
for _, data := range canvasNodeData(raw) {
id, _ := data["assetId"].(string)
if id == "" {
src, _ := data["src"].(string)
prefix := s.assetURL(project, workspace, "")
if strings.HasPrefix(src, prefix) {
candidate := strings.TrimPrefix(src, prefix)
if uuidSlugPattern.MatchString(candidate) {
id = candidate
}
}
}
if id == "" {
continue
}
_, err := tx.ExecContext(r.Context(), `INSERT INTO canvas_asset_bindings(project,workspace_id,asset_id,board_id) VALUES($1,$2,$3,$4) ON CONFLICT DO NOTHING`, project, workspace, id, board)
if err != nil {
return err
}
}
return nil
}
// validateCanvasAssets 对托管 URL 强制 ID/URL 一致并实时验证可读性,合法引用在同事务中建立当前画布绑定。
// 普通外部图片 URL 在此跳过,交给快照结构校验;它们不会成为私有资产绑定。
func (s *service) validateCanvasAssets(r *http.Request, tx *sql.Tx, project, workspace, account string, raw json.RawMessage) (bool, error) {
for _, data := range canvasNodeData(raw) {
id, explicit := data["assetId"].(string)
if !explicit {
src, _ := data["src"].(string)
prefix := s.assetURL(project, workspace, "")
if !strings.HasPrefix(src, prefix) {
continue
}
id = strings.TrimPrefix(src, prefix)
if !uuidSlugPattern.MatchString(id) {
return false, nil
}
}
if data["src"] != s.assetURL(project, workspace, id) {
return false, nil
}
allowed, err := assetReadable(r, tx, project, workspace, id, account)
if err == sql.ErrNoRows {
return false, nil
}
if err != nil {
return false, err
}
if !allowed {
return false, nil
}
// assetId is optional. Stable managed URLs acquire the same durable binding.
_, err = tx.ExecContext(r.Context(), `INSERT INTO canvas_asset_bindings(project,workspace_id,asset_id,board_id) VALUES($1,$2,$3,$4) ON CONFLICT DO NOTHING`, project, workspace, id, r.PathValue("material"))
if err != nil {
return false, err
}
}
return true, nil
}
-43
View File
@@ -1,43 +0,0 @@
// 资产解码纯函数回归,编码小型真实栅格样本后检查格式与尺寸,不访问数据库。
package platform
import (
"bytes"
"image"
"image/color"
"image/gif"
"image/jpeg"
"image/png"
"testing"
)
// TestAssetDecodersUseActualContent 验证 PNG/JPEG/GIF 从实际内容识别,拒绝截断样本和未支持的 SVG。
func TestAssetDecodersUseActualContent(t *testing.T) {
im := image.NewRGBA(image.Rect(0, 0, 3, 2))
im.Set(1, 1, color.RGBA{R: 255, A: 255})
for _, format := range []string{"png", "jpeg", "gif"} {
var encoded bytes.Buffer
var err error
switch format {
case "png":
err = png.Encode(&encoded, im)
case "jpeg":
err = jpeg.Encode(&encoded, im, nil)
case "gif":
err = gif.Encode(&encoded, im, nil)
}
if err != nil {
t.Fatal(err)
}
mime, width, height, err := inspectAsset(encoded.Bytes())
if err != nil || mime != "image/"+format || width != 3 || height != 2 {
t.Fatalf("%s decoded %s %dx%d: %v", format, mime, width, height, err)
}
if _, _, _, err := inspectAsset(encoded.Bytes()[:len(encoded.Bytes())/2]); err == nil {
t.Errorf("truncated %s accepted", format)
}
}
if _, _, _, err := inspectAsset([]byte("<svg xmlns='http://www.w3.org/2000/svg'></svg>")); err == nil {
t.Fatal("SVG accepted")
}
}
-457
View File
@@ -1,457 +0,0 @@
// 画布快照协议的结构规范化与旧整文档 GET/PATCH;跨画布所有权变更必须走专用事务命令。
package platform
import (
"encoding/base64"
"encoding/json"
"io"
"math"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"unicode/utf8"
)
// canvasLimit 同时约束快照文档及该路由请求体预算,较大的嵌入图片也计算在内。
const canvasLimit = 5 << 20
var canvasColor = regexp.MustCompile(`^#[0-9a-fA-F]{6}$`)
var canvasID = regexp.MustCompile(`^[A-Za-z0-9_-]{1,128}$`)
var canvasIcon = regexp.MustCompile(`^[A-Z][A-Za-z0-9]{0,63}$`)
// canvasNumber 面向 JSON 解码后的 float64,拒绝非数、无穷和超出闭区间的值。
func canvasNumber(v any, low, high float64) bool {
n, ok := v.(float64)
return ok && !math.IsNaN(n) && !math.IsInf(n, 0) && n >= low && n <= high
}
// canvasString 按 Unicode 码点数限制展示文本,与请求体的字节预算分别约束。
func canvasString(v any, limit int) bool {
s, ok := v.(string)
return ok && utf8.RuneCountInString(s) <= limit
}
// canvasChoice 用于协议枚举白名单;缺省字段由调用处决定是否允许,不能自动匹配零值。
func canvasChoice(v any, choices ...string) bool {
for _, s := range choices {
if v == s {
return true
}
}
return false
}
// canvasFields 拒绝 nil 和未知键,但不要求所有允许键都存在;必填性由后续类型/值检查保证。
func canvasFields(m map[string]any, fields ...string) bool {
if m == nil {
return false
}
for k := range m {
found := false
for _, f := range fields {
if k == f {
found = true
break
}
}
if !found {
return false
}
}
return true
}
// canvasImage 接受无用户信息的 HTTPS URL,或最多 2 MiB 且 MIME 嗅探相符的栅格 data URL。
// 此处不下载 HTTPS 图片,内嵌图也只做头部嗅探,不承担完整图片解码。
func canvasImage(v any) bool {
s, ok := v.(string)
if !ok {
return false
}
if strings.HasPrefix(s, "https://") {
u, e := url.Parse(s)
return e == nil && u.Hostname() != "" && u.User == nil && len(s) < 2048
}
for _, mime := range []string{"png", "jpeg", "webp", "gif"} {
prefix := "data:image/" + mime + ";base64,"
if strings.HasPrefix(s, prefix) {
b, e := base64.StdEncoding.DecodeString(strings.TrimPrefix(s, prefix))
return e == nil && len(b) > 0 && len(b) <= 2<<20 && http.DetectContentType(b) == "image/"+mime
}
}
return false
}
// normalizeCanvas 验证 v1/v2 文档,移除界面临时状态,再重编码为持久快照。
// 仅校验单文档结构;数据库所有权、模型能力与资产权限仍由保存流程另行检查。
func normalizeCanvas(raw json.RawMessage) (json.RawMessage, bool) {
if len(raw) > canvasLimit {
return nil, false
}
var doc map[string]any
if json.Unmarshal(raw, &doc) != nil || !canvasFields(doc, "schema_version", "nodes", "edges", "viewport") || (doc["schema_version"] != float64(1) && doc["schema_version"] != float64(2)) {
return nil, false
}
v2 := doc["schema_version"] == float64(2)
nodes, ok := doc["nodes"].([]any)
if !ok || len(nodes) > 500 {
return nil, false
}
edges, ok := doc["edges"].([]any)
if !ok || len(edges) > 2000 {
return nil, false
}
viewport, ok := doc["viewport"].(map[string]any)
if !ok || !canvasFields(viewport, "x", "y", "zoom") || !canvasNumber(viewport["x"], -math.MaxFloat64, math.MaxFloat64) || !canvasNumber(viewport["y"], -math.MaxFloat64, math.MaxFloat64) || !canvasNumber(viewport["zoom"], .1, 4) {
return nil, false
}
if v2 && (!canvasNumber(viewport["x"], -1e6, 1e6) || !canvasNumber(viewport["y"], -1e6, 1e6)) {
return nil, false
}
// 先收集节点类型和框端口,第二遍才检查 frameId/边引用,因此允许合法的前向引用。
kinds := map[string]string{}
framePorts := map[string]map[string]string{}
for _, v := range nodes {
n, ok := v.(map[string]any)
if !ok {
return nil, false
}
// 兼容前端 style 中的测量尺寸,但显式 width/height 优先;随后去除 selected/dragging 等临时状态。
if style, ok := n["style"].(map[string]any); ok {
if _, exists := n["width"]; !exists {
if v, exists := style["width"]; exists {
n["width"] = v
}
}
if _, exists := n["height"]; !exists {
if v, exists := style["height"]; exists {
n["height"] = v
}
}
}
for _, key := range []string{"selected", "dragging", "measured", "style", "zIndex"} {
delete(n, key)
}
if !canvasFields(n, "id", "type", "position", "width", "height", "data") {
return nil, false
}
id, ok := n["id"].(string)
if !ok || !canvasID.MatchString(id) || kinds[id] != "" {
return nil, false
}
p, ok := n["position"].(map[string]any)
if !ok || !canvasFields(p, "x", "y") || !canvasNumber(p["x"], -1e6, 1e6) || !canvasNumber(p["y"], -1e6, 1e6) {
return nil, false
}
_, w := n["width"]
_, h := n["height"]
// 普通节点与 v2 frame 使用不同尺寸预算,宽高必须同时缺省或同时合法。
low, high := float64(20), float64(3000)
if data, _ := n["data"].(map[string]any); v2 && data["kind"] == "frame" {
low, high = 32, 100000
}
if w != h || (w && (!canvasNumber(n["width"], low, high) || !canvasNumber(n["height"], low, high))) {
return nil, false
}
d, ok := n["data"].(map[string]any)
if !ok || !canvasFields(d, "kind", "title", "text", "src", "icon", "rotation", "fontSize", "textStyle", "frameId", "labelMode", "subgraph", "presentation", "ports", "assetId", "ai") {
return nil, false
}
if ai, exists := d["ai"]; exists {
kind, _ := d["kind"].(string)
if !v2 || !validCanvasAI(ai, kind) {
return nil, false
}
}
if !validCanvasFrameExtensions(d, v2) {
return nil, false
}
if id, exists := d["assetId"]; exists {
value, ok := id.(string)
if !v2 || !ok || !uuidSlugPattern.MatchString(value) || !canvasChoice(d["kind"], "image", "plain-image") {
return nil, false
}
}
kind, ok := d["kind"].(string)
if !ok {
return nil, false
}
typ := "material"
if kind == "plain-text" {
typ = "plainText"
} else if kind == "plain-image" {
typ = "plainImage"
} else if kind == "icon" {
typ = "icon"
} else if kind == "frame" {
typ = "frame"
} else if !canvasChoice(kind, "text", "image", "script") {
return nil, false
}
if n["type"] != typ || !canvasString(d["title"], 300) || !canvasString(d["text"], 100000) {
return nil, false
}
if frameID, exists := d["frameId"]; exists {
value, ok := frameID.(string)
if kind == "frame" || !ok || !canvasID.MatchString(value) {
return nil, false
}
}
if mode, exists := d["labelMode"]; exists && (kind != "frame" || !canvasChoice(mode, "hidden", "fixed", "scaled")) {
return nil, false
}
if kind == "frame" {
if rotation, exists := d["rotation"]; exists && rotation != float64(0) {
return nil, false
}
}
// validCanvasFrameExtensions 已检查端口对象形状,此处建立方向索引供边端点验证。
if kind == "frame" && v2 {
ports := map[string]string{}
if values, ok := d["ports"].([]any); ok {
for _, v := range values {
p := v.(map[string]any)
ports[p["id"].(string)] = p["direction"].(string)
}
}
framePorts[id] = ports
}
kinds[id] = kind
if r, exists := d["rotation"]; exists && (!canvasNumber(r, 0, 360) || r == float64(360)) {
return nil, false
}
if f, exists := d["fontSize"]; exists && !canvasNumber(f, 8, 160) {
return nil, false
}
if kind == "icon" {
s, ok := d["icon"].(string)
if !ok || !canvasIcon.MatchString(s) {
return nil, false
}
}
if src, exists := d["src"]; (exists || kind == "image" || kind == "plain-image") && !canvasImage(src) {
return nil, false
}
if value, exists := d["textStyle"]; exists {
style, ok := value.(map[string]any)
if !ok || !canvasFields(style, "color", "background", "bold", "italic", "underline", "align", "fontFamily", "lineHeight") {
return nil, false
}
for k, v := range style {
switch k {
case "color", "background":
s, ok := v.(string)
if !ok || !(canvasColor.MatchString(s) || (k == "background" && s == "transparent")) {
return nil, false
}
case "bold", "italic", "underline":
if _, ok := v.(bool); !ok {
return nil, false
}
case "align":
if !canvasChoice(v, "left", "center", "right") {
return nil, false
}
case "fontFamily":
if !canvasChoice(v, "sans", "serif", "mono") {
return nil, false
}
case "lineHeight":
if !canvasNumber(v, 1, 3) {
return nil, false
}
}
}
}
}
// Resolve memberships after all nodes so forward references are valid.
// Geometry never creates membership: only explicit frameId is persisted.
// 成员关系只由显式 frameId 决定,几何重叠不产生所有权;框本身不能成为框成员。
for _, value := range nodes {
data := value.(map[string]any)["data"].(map[string]any)
if id, exists := data["frameId"]; exists && kinds[id.(string)] != "frame" {
return nil, false
}
}
seen := map[string]bool{}
for _, v := range edges {
e, ok := v.(map[string]any)
if !ok {
return nil, false
}
delete(e, "selected")
fields := []string{"id", "source", "target", "sourceHandle", "targetHandle", "type"}
if v2 {
fields = append(fields, "data")
}
if !canvasFields(e, fields...) {
return nil, false
}
id, ok := e["id"].(string)
if !ok || !canvasID.MatchString(id) || seen[id] {
return nil, false
}
seen[id] = true
for _, key := range []string{"source", "target"} {
s, ok := e[key].(string)
if !ok {
return nil, false
}
// 边连接 frame 时必须使用已声明端口,源只能 output,目标只能 input。
if v2 && kinds[s] == "frame" {
handle, _ := e[key+"Handle"].(string)
direction := "input"
if key == "source" {
direction = "output"
}
if !strings.HasPrefix(handle, "port:") || framePorts[s][strings.TrimPrefix(handle, "port:")] != direction {
return nil, false
}
continue
}
if !(canvasChoice(kinds[s], "text", "image", "script") || (v2 && canvasChoice(kinds[s], "plain-text", "plain-image"))) {
return nil, false
}
}
for _, key := range []string{"sourceHandle", "targetHandle"} {
endpoint := strings.TrimSuffix(key, "Handle")
id, _ := e[endpoint].(string)
if v2 && kinds[id] == "frame" {
continue
}
if h, exists := e[key]; exists && h != nil && !canvasChoice(h, "", "top", "right", "bottom", "left") {
return nil, false
}
}
if data, exists := e["data"]; exists && (!v2 || !validCanvasEdgeData(data)) {
return nil, false
}
if typ, exists := e["type"]; exists && !canvasChoice(typ, "default", "bezier") {
return nil, false
}
}
out, err := json.Marshal(doc)
return out, err == nil
}
// canvas 读取时在发送响应体前释放事务;保存时将文档、资产绑定及 AI 目标失效一并提交。
func (s *service) canvas(w http.ResponseWriter, r *http.Request, project, account string) error {
if r.Method != http.MethodGet && r.Method != http.MethodPatch {
reject(w, 405, "method_not_allowed")
return nil
}
tx, err := s.db.BeginTx(r.Context(), nil)
if err != nil {
return err
}
defer tx.Rollback()
workspace, material := r.PathValue("workspace"), r.PathValue("material")
kind, role, err := lockMaterial(r.Context(), tx, project, workspace, material, account)
if err != nil {
return err
}
if kind != "board" {
reject(w, 400, "invalid_material")
return nil
}
var version int64
var document json.RawMessage
err = tx.QueryRowContext(r.Context(), `SELECT canvas_version,COALESCE(canvas_document,'{"schema_version":1,"nodes":[],"edges":[],"viewport":{"x":0,"y":0,"zoom":1}}'::jsonb) FROM materials WHERE project=$1 AND workspace_id=$2 AND id=$3`, project, workspace, material).Scan(&version, &document)
if err != nil {
return err
}
if canvasSchema(document) == 2 && !acceptsCanvasV2(r) {
reject(w, 409, "canvas_schema_upgrade_required")
return nil
}
if r.Method == http.MethodGet {
if err = tx.Rollback(); err != nil {
return err
}
w.Header().Set("X-Canvas-Schema-Version", strconv.Itoa(canvasSchema(document)))
setVersion(w, version)
reply(w, 200, response{"version": version, "document": document})
return nil
}
if role == "viewer" {
reject(w, 403, "forbidden")
return nil
}
expected, ok := expectedVersion(w, r)
if !ok {
return nil
}
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, canvasLimit))
if err != nil {
reject(w, 413, "canvas_too_large")
return nil
}
var input struct {
Document json.RawMessage `json:"document"`
}
decoder := json.NewDecoder(strings.NewReader(string(body)))
decoder.DisallowUnknownFields()
if !utf8.Valid(body) || decoder.Decode(&input) != nil || decoder.Decode(new(any)) != io.EOF {
reject(w, 400, "invalid_canvas")
return nil
}
if canvasExceededGraphLimits(input.Document) {
reject(w, 413, "graph_limit_exceeded")
return nil
}
previousDocument := document
previousSchema := canvasSchema(document)
document, ok = normalizeCanvas(input.Document)
if !ok {
reject(w, 400, "invalid_canvas")
return nil
}
if canvasSchema(document) == 2 && !acceptsCanvasV2(r) {
reject(w, 409, "canvas_schema_upgrade_required")
return nil
}
// 已升级文档不可通过旧客户端降回 v1,避免丢失子图和端口等结构。
if previousSchema == 2 && canvasSchema(document) != 2 {
reject(w, 409, "canvas_schema_upgrade_required")
return nil
}
if expected != version {
reject(w, 412, "version_conflict")
return nil
}
// 通过版本检查后仍须保持现有跨画布关系;普通快照不能自行创建或重定向所有权。
if valid, e := validateCanvasRelations(r, tx, project, workspace, material, previousDocument, document); e != nil {
return e
} else if !valid {
reject(w, 409, "ownership_conflict")
return nil
}
if !s.validateCanvasAIModels(w, r, document) {
return nil
}
if valid, e := s.validateCanvasAssets(r, tx, project, workspace, account, document); e != nil {
return e
} else if !valid {
reject(w, 400, "invalid_asset_reference")
return nil
}
// 在相同事务中建立资产引用、使被删除/改变的 AI 目标失效,再推进独立的 canvas_version。
if err = s.attachCanvasAssets(r, tx, project, workspace, material, document); err != nil {
return err
}
if err = invalidateCanvasAITargets(r, tx, project, workspace, material, previousDocument, document); err != nil {
return err
}
_, err = tx.ExecContext(r.Context(), `UPDATE materials SET canvas_document=$4,canvas_version=canvas_version+1 WHERE project=$1 AND workspace_id=$2 AND id=$3`, project, workspace, material, document)
if err != nil {
return err
}
if err = tx.Commit(); err != nil {
return err
}
setVersion(w, version+1)
reply(w, 200, response{"version": version + 1})
return nil
}
-312
View File
@@ -1,312 +0,0 @@
// AI 步骤开始/完成的事务边界:执行前与回写前分别校验权限、租约和目标身份,防止迟到输出覆盖新状态。
package platform
import (
"context"
"database/sql"
"encoding/json"
"errors"
"gitea.entroia.com/Zayden-Jung/foundry-core/internal/codex"
)
// startCanvasStep 持工作区锁解析目标当前 owner,再检查租约、编辑权限与内容指纹,成功才将 queued 改 running。
// 不可执行时先释放事务,再调用完成流程记录拒绝状态,避免嵌套事务互锁。
func (s *service) startCanvasStep(ctx context.Context, run canvasQueueRun, step canvasAIStepPlan) (bool, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return false, err
}
defer tx.Rollback()
if err = lockCanvasAIWorkspace(ctx, tx, run.Project, run.Workspace); err != nil {
return false, err
}
board, identityOK, err := resolveCanvasAITarget(ctx, tx, run.Project, run.Workspace, step)
if err != nil {
return false, err
}
if !identityOK {
tx.Rollback()
_, err = s.finishCanvasStep(ctx, run, step, "", "target_removed", false)
return false, err
}
_, role, permissionErr := lockMaterial(ctx, tx, run.Project, run.Workspace, board, run.Account)
if permissionErr != nil || role == "viewer" {
tx.Rollback()
if permissionErr != nil && permissionErr != sql.ErrNoRows {
return false, permissionErr
}
_, err = s.finishCanvasStep(ctx, run, step, "", "permission_revoked", false)
return false, err
}
var active bool
err = tx.QueryRowContext(ctx, `SELECT status='running' AND lease_id=$4 AND NOT cancel_requested FROM canvas_ai_runs WHERE project=$1 AND workspace_id=$2 AND id=$3 FOR UPDATE`, run.Project, run.Workspace, run.ID, run.Lease).Scan(&active)
if err != nil {
return false, err
}
if !active {
tx.Rollback()
_, err = s.finishCanvasStep(ctx, run, step, "", "generation_cancelled", false)
return false, err
}
snapshot, err := loadCanvas(queueRequest(ctx), tx, run.Project, run.Workspace, board)
if err != nil {
return false, err
}
data := canvasNodeData(snapshot.Document)[step.NodeID]
if !identityOK || data == nil || canvasTargetFingerprint(step.BoardID, step.NodeID, data) != step.Fingerprint {
tx.Rollback()
_, err = s.finishCanvasStep(ctx, run, step, "", "target_changed", false)
return false, err
}
result, err := tx.ExecContext(ctx, `UPDATE canvas_ai_steps SET status='running',started_at=now() WHERE project=$1 AND workspace_id=$2 AND run_id=$3 AND id=$4 AND status='queued'`, run.Project, run.Workspace, run.ID, step.ID)
if err != nil {
return false, err
}
count, _ := result.RowsAffected()
if count != 1 {
return false, nil
}
if err = appendAIEvent(ctx, tx, run.Project, run.Workspace, run.ID, "step.running", response{"step_id": step.ID, "board_id": step.BoardID, "node_id": step.NodeID}); err != nil {
return false, err
}
for _, edge := range run.Plan.Edges {
if edge.Target == step.ID {
if err = appendAIEvent(ctx, tx, run.Project, run.Workspace, run.ID, "edge.active", response{"logical_edge_id": edge.ID, "step_id": step.ID, "status": "active"}); err != nil {
return false, err
}
}
}
if err = tx.Commit(); err != nil {
return false, err
}
return true, nil
}
// finishCanvasStep 是文本/无输出失败路径的兼容包装,所有落库与事件逻辑集中在结构化完成函数。
func (s *service) finishCanvasStep(ctx context.Context, run canvasQueueRun, step canvasAIStepPlan, text, code string, started bool) (string, error) {
return s.finishCanvasStepOutput(ctx, run, step, codex.CanvasOutput{Kind: "text", Text: text}, code, started)
}
// finishCanvasStepOutput 在同一事务中保存输出、条件应用、步骤终态与事件;已终态或租约失效则直接保留旧结果。
func (s *service) finishCanvasStepOutput(ctx context.Context, run canvasQueueRun, step canvasAIStepPlan, generated codex.CanvasOutput, code string, started bool) (string, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return "", err
}
defer tx.Rollback()
var locked string
err = tx.QueryRowContext(ctx, `SELECT id::text FROM workspaces WHERE project=$1 AND id=$2 FOR UPDATE`, run.Project, run.Workspace).Scan(&locked)
if err != nil {
return "", err
}
var runStatus string
var cancelled bool
var lease sql.NullString
err = tx.QueryRowContext(ctx, `SELECT status,cancel_requested,lease_id::text FROM canvas_ai_runs WHERE project=$1 AND workspace_id=$2 AND id=$3 FOR UPDATE`, run.Project, run.Workspace, run.ID).Scan(&runStatus, &cancelled, &lease)
if err != nil {
return "", err
}
var oldStatus string
err = tx.QueryRowContext(ctx, `SELECT status FROM canvas_ai_steps WHERE project=$1 AND workspace_id=$2 AND run_id=$3 AND id=$4 FOR UPDATE`, run.Project, run.Workspace, run.ID, step.ID).Scan(&oldStatus)
if err != nil {
return "", err
}
// 取消、删除失效和其他完成者已写出的终态优先,迟到 worker 结果不得改回成功。
if oldStatus != "queued" && oldStatus != "running" {
return oldStatus, nil
}
if runStatus != "running" || !lease.Valid || lease.String != run.Lease {
return oldStatus, nil
}
// 统一映射依赖失败、内容冲突、取消与生成错误,run.cancel_requested 优先于局部生成结果。
status := "succeeded"
switch code {
case "dependency_failed":
status = "skipped"
case "target_changed":
status = "conflict"
case "generation_cancelled", "target_removed":
status = "cancelled"
default:
if code != "" {
status = "failed"
}
}
if cancelled {
status = "cancelled"
code = "generation_cancelled"
}
board, identityOK, err := resolveCanvasAITarget(ctx, tx, run.Project, run.Workspace, step)
if err != nil {
return "", err
}
eventBoard := board
if !identityOK {
eventBoard = step.BoardID
}
var appliedBoard any
var appliedEvent response
var output any
var version any
// 生成成功才保存可供恢复的输出;内容指纹冲突时仍保留 output,但不覆盖当前节点。
if code == "" && started {
var outputID string
err = tx.QueryRowContext(ctx, `SELECT gen_random_uuid()::text`).Scan(&outputID)
if err != nil {
return "", err
}
patch := response{}
if generated.Kind == "image" {
imageOutput, err := s.persistCanvasImage(ctx, tx, run, outputID, generated.Image)
if err != nil {
return "", err
}
output = imageOutput
patch["src"] = imageOutput["src"]
patch["assetId"] = imageOutput["assetId"]
} else {
output = response{"output_id": outputID, "kind": "text", "text": generated.Text}
patch["text"] = generated.Text
}
_, role, permissionErr := lockCanvasAIRunRoute(ctx, tx, run.Project, run.Workspace, eventBoard, run.Account)
if permissionErr != nil && permissionErr != sql.ErrNoRows {
return "", permissionErr
}
if permissionErr != nil || role == "viewer" {
status = "failed"
code = "permission_revoked"
} else {
snapshot, err := loadCanvas(queueRequest(ctx), tx, run.Project, run.Workspace, eventBoard)
if err != nil {
return "", err
}
target := canvasNodeData(snapshot.Document)[step.NodeID]
if image, ok := output.(response); ok && image["kind"] == "image" && identityOK {
if _, err = tx.ExecContext(ctx, `INSERT INTO canvas_asset_bindings(project,workspace_id,asset_id,board_id) VALUES($1,$2,$3,$4) ON CONFLICT DO NOTHING`, run.Project, run.Workspace, image["assetId"], eventBoard); err != nil {
return "", err
}
}
// 仍使用原计划来源构造指纹,owner 变化由 canonical 稳定身份单独解析,拖动不造成假冲突。
if !identityOK || target == nil || canvasTargetFingerprint(step.BoardID, step.NodeID, target) != step.Fingerprint {
status, code = "conflict", "target_changed"
} else {
change, err := prepareCanvasAIPatch(queueRequest(ctx), tx, run.Project, run.Workspace, snapshot, step.NodeID, patch)
if err != nil {
if !errors.Is(err, errAIInvalidPatch) && !errors.Is(err, errCanvasModel) && !errors.Is(err, errGraphCapacity) {
return "", err
}
status, code = "failed", "generation_output_too_large"
} else {
if err = s.saveCanvasAIChange(queueRequest(ctx), tx, run.Project, run.Workspace, run.Account, change); err != nil {
return "", err
}
version = change.Snapshot.Version
appliedBoard = eventBoard
applied := response{"step_id": step.ID, "board_id": eventBoard, "node_id": step.NodeID, "patch": patch, "canvas_version": change.Snapshot.Version}
change.addTargetContext(applied, step)
appliedEvent = applied
}
}
}
}
// output 与 applied 是不同事件;换 owner 后的冲突附完整模型,客户端可定位当前显式应用目标。
if output != nil {
event := response{"step_id": step.ID, "board_id": eventBoard, "origin_board_id": step.BoardID, "canonical_root": step.CanonicalRoot, "target_incarnation": step.TargetIncarnation, "node_id": step.NodeID, "output": output}
if status == "conflict" && identityOK && step.CanonicalRoot != "" && eventBoard != step.BoardID {
model, e := loadCanvasModel(ctx, tx, run.Project, run.Workspace, step.CanonicalRoot)
if e != nil {
return "", e
}
event["model"], event["document_format_version"], event["canvas_version"] = model.view(nil), canvasModelFormat, model.Versions[eventBoard]
}
if err = appendAIEvent(ctx, tx, run.Project, run.Workspace, run.ID, "step.output", event); err != nil {
return "", err
}
}
if appliedEvent != nil {
if err = appendAIEvent(ctx, tx, run.Project, run.Workspace, run.ID, "step.applied", appliedEvent); err != nil {
return "", err
}
}
var outputJSON any
if output != nil {
encoded, _ := json.Marshal(output)
outputJSON = encoded
}
_, err = tx.ExecContext(ctx, `UPDATE canvas_ai_steps SET status=$5,output=$6,error_code=NULLIF($7,''),applied_version=$8,applied_board_id=$9,completed_at=now() WHERE project=$1 AND workspace_id=$2 AND run_id=$3 AND id=$4`, run.Project, run.Workspace, run.ID, step.ID, status, outputJSON, code, version, appliedBoard)
if err != nil {
return "", err
}
if status != "succeeded" {
if err = appendAIEvent(ctx, tx, run.Project, run.Workspace, run.ID, "step."+status, response{"step_id": step.ID, "board_id": step.BoardID, "node_id": step.NodeID, "status": status, "error": code}); err != nil {
return "", err
}
}
edgeStatus := "completed"
if status == "failed" || status == "conflict" {
edgeStatus = "failed"
} else if status != "succeeded" {
edgeStatus = "skipped"
}
for _, edge := range run.Plan.Edges {
if edge.Target == step.ID {
if err = appendAIEvent(ctx, tx, run.Project, run.Workspace, run.ID, "edge."+edgeStatus, response{"logical_edge_id": edge.ID, "step_id": step.ID, "status": edgeStatus}); err != nil {
return "", err
}
}
}
if err = tx.Commit(); err != nil {
return "", err
}
return status, nil
}
// completeCanvasRun 从数据库步骤聚合实际终态而非信任内存 results;仍有活跃步骤则不提前结束 run。
// 仅当前租约可清空租约并写 run.completed,兼容部分成功、全冲突和取消。
func (s *service) completeCanvasRun(ctx context.Context, run canvasQueueRun, _ map[string]canvasStepResult) error {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
var status string
var cancelled bool
var lease sql.NullString
err = tx.QueryRowContext(ctx, `SELECT status,cancel_requested,lease_id::text FROM canvas_ai_runs WHERE project=$1 AND workspace_id=$2 AND id=$3 FOR UPDATE`, run.Project, run.Workspace, run.ID).Scan(&status, &cancelled, &lease)
if err != nil {
return err
}
if status != "running" || !lease.Valid || lease.String != run.Lease {
return nil
}
var succeeded, failed, conflicts, cancelledSteps, active int
err = tx.QueryRowContext(ctx, `SELECT count(*) FILTER(WHERE status='succeeded'),count(*) FILTER(WHERE status='failed'),count(*) FILTER(WHERE status='conflict'),count(*) FILTER(WHERE status='cancelled'),count(*) FILTER(WHERE status IN('queued','running')) FROM canvas_ai_steps WHERE project=$1 AND workspace_id=$2 AND run_id=$3`, run.Project, run.Workspace, run.ID).Scan(&succeeded, &failed, &conflicts, &cancelledSteps, &active)
if err != nil {
return err
}
if active > 0 {
return nil
}
status = "succeeded"
if cancelled {
status = "cancelled"
} else if failed+conflicts+cancelledSteps > 0 {
status = "failed"
if succeeded > 0 {
status = "partially_succeeded"
} else if cancelledSteps > 0 && failed+conflicts == 0 {
status = "cancelled"
} else if conflicts > 0 && failed == 0 {
status = "conflict"
}
}
_, err = tx.ExecContext(ctx, `UPDATE canvas_ai_runs SET status=$4,completed_at=now(),lease_id=NULL,lease_until=NULL WHERE project=$1 AND workspace_id=$2 AND id=$3`, run.Project, run.Workspace, run.ID, status)
if err != nil {
return err
}
if err = appendAIEvent(ctx, tx, run.Project, run.Workspace, run.ID, "run.completed", response{"status": status}); err != nil {
return err
}
return tx.Commit()
}
-210
View File
@@ -1,210 +0,0 @@
// 用户取消 AI run:立即冻结数据库终态与回执,worker 心跳在随后一秒级检查中停止在途调用。
package platform
import (
"database/sql"
"encoding/json"
"io"
"net/http"
)
// cancelCanvasAIRun 接受旧空体或完整 v2 身份;重试先返回原回执,再决定是否需要取消 queued/running 步骤。
func (s *service) cancelCanvasAIRun(w http.ResponseWriter, r *http.Request, project, account string) error {
if r.Method != http.MethodPost {
reject(w, 405, "method_not_allowed")
return nil
}
key, id := canvasIdempotencyKey(r), r.PathValue("run")
if !uuidSlugPattern.MatchString(key) || !uuidSlugPattern.MatchString(id) {
reject(w, 400, "invalid_ai_request")
return nil
}
raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 4096))
if err != nil {
reject(w, 413, "context_too_large")
return nil
}
var input struct {
ProtocolVersion int `json:"protocol_version,omitempty"`
RequestID string `json:"request_id,omitempty"`
OperationID string `json:"operation_id,omitempty"`
}
if len(raw) > 0 && (json.Unmarshal(raw, &input) != nil || string(raw) == "null") {
reject(w, 400, "invalid_ai_request")
return nil
}
var fields map[string]any
if len(raw) > 0 {
if json.Unmarshal(raw, &fields) != nil || fields == nil {
reject(w, 400, "invalid_ai_request")
return nil
}
for key := range fields {
if key != "protocol_version" && key != "request_id" && key != "operation_id" {
reject(w, 400, "invalid_ai_request")
return nil
}
}
}
canonical := input.ProtocolVersion != 0 || input.RequestID != "" || input.OperationID != ""
if canonical && (input.ProtocolVersion != 2 || input.RequestID != key || !uuidSlugPattern.MatchString(input.OperationID) || !acceptsCanvasV2(r)) {
reject(w, 400, "invalid_ai_protocol")
return nil
}
if !canonical && len(fields) > 0 {
reject(w, 400, "invalid_ai_request")
return nil
}
hash := payloadDigest(map[string]any{})
if canonical {
hash = payloadDigest(input)
}
workspace, board := r.PathValue("workspace"), r.PathValue("material")
tx, err := s.db.BeginTx(r.Context(), nil)
if err != nil {
return err
}
defer tx.Rollback()
_, role, err := lockCanvasAIRunRoute(r.Context(), tx, project, workspace, board, account)
if err != nil {
return err
}
var receipt *canvasAIRequest
if canonical {
receipt = &canvasAIRequest{Key: key, Hash: hash, Action: "run.cancel", Board: board, Run: id, Operation: input.OperationID}
if done, e := beginCanvasAIRequest(w, r, tx, project, workspace, account, receipt); done || e != nil {
return e
}
}
rejectRequest := func(status int, code string) error {
return rejectCanvasAIRequest(w, r, tx, project, workspace, account, receipt, status, code)
}
if role == "viewer" {
return rejectRequest(403, "forbidden")
}
var status string
var rawPlan json.RawMessage
err = tx.QueryRowContext(r.Context(), `SELECT status,plan FROM canvas_ai_runs WHERE project=$1 AND workspace_id=$2 AND board_id=$3 AND id=$4 FOR UPDATE`, project, workspace, board, id).Scan(&status, &rawPlan)
if err == sql.ErrNoRows {
return rejectRequest(404, "not_found")
}
if err != nil {
return err
}
var priorHash string
var prior json.RawMessage
err = tx.QueryRowContext(r.Context(), `SELECT payload_hash,response_body FROM canvas_ai_mutations WHERE project=$1 AND workspace_id=$2 AND run_id=$3 AND account_id=$4 AND action='cancel' AND idempotency_key=$5`, project, workspace, id, account, key).Scan(&priorHash, &prior)
if err == nil {
if priorHash != hash {
reject(w, 409, "idempotency_conflict")
return nil
}
reply(w, 200, prior)
return nil
}
if err != sql.ErrNoRows {
return err
}
var plan canvasAIPlan
if err = json.Unmarshal(rawPlan, &plan); err != nil {
return err
}
// 取消也要求所有步骤当前目标可编辑,目标移动后按新 owner 权限判断,不能借原 run 路径越权。
for _, step := range plan.Steps {
target, ok, e := resolveCanvasAITarget(r.Context(), tx, project, workspace, step)
if e != nil {
return e
}
if !ok {
target = step.BoardID
}
_, role, err := lockCanvasAIRunRoute(r.Context(), tx, project, workspace, target, account)
if err != nil {
return err
}
if role == "viewer" {
return rejectRequest(403, "forbidden")
}
}
// 已成功的步骤不回滚;只把仍活跃步骤设 cancelled,并为受影响边写 skipped 事件。
if status == "queued" || status == "running" {
_, err = tx.ExecContext(r.Context(), `UPDATE canvas_ai_runs SET status='cancelled',cancel_requested=true,completed_at=now() WHERE project=$1 AND workspace_id=$2 AND id=$3`, project, workspace, id)
if err != nil {
return err
}
rows, err := tx.QueryContext(r.Context(), `UPDATE canvas_ai_steps SET status='cancelled',error_code='generation_cancelled',completed_at=now() WHERE project=$1 AND workspace_id=$2 AND run_id=$3 AND status IN('queued','running') RETURNING id,board_id::text,node_id`, project, workspace, id)
if err != nil {
return err
}
events := []response{}
for rows.Next() {
var step, board, node string
if err = rows.Scan(&step, &board, &node); err != nil {
break
}
events = append(events, response{"step_id": step, "board_id": board, "node_id": node, "status": "cancelled"})
}
if err == nil {
err = rows.Err()
}
rows.Close()
if err != nil {
return err
}
cancelled := map[string]bool{}
for _, event := range events {
cancelled[event["step_id"].(string)] = true
if err = appendAIEvent(r.Context(), tx, project, workspace, id, "step.cancelled", event); err != nil {
return err
}
}
for _, edge := range plan.Edges {
if cancelled[edge.Target] {
if err = appendAIEvent(r.Context(), tx, project, workspace, id, "edge.skipped", response{"logical_edge_id": edge.ID, "status": "skipped"}); err != nil {
return err
}
}
}
status = "cancelled"
if err = appendAIEvent(r.Context(), tx, project, workspace, id, "run.completed", response{"status": status}); err != nil {
return err
}
}
rows, err := tx.QueryContext(r.Context(), `SELECT id,COALESCE(applied_board_id,board_id)::text,node_id,status,applied_version FROM canvas_ai_steps WHERE project=$1 AND workspace_id=$2 AND run_id=$3 ORDER BY ordinal`, project, workspace, id)
if err != nil {
return err
}
// 回执分别列出此前已经应用的版本与本次/既有取消步骤,避免把取消误解为撤销所有已生效结果。
applied, cancelledSteps := []any{}, []any{}
for rows.Next() {
var step, board, node, state string
var version sql.NullInt64
if err = rows.Scan(&step, &board, &node, &state, &version); err != nil {
break
}
if version.Valid {
applied = append(applied, response{"step_id": step, "board_id": board, "node_id": node, "canvas_version": version.Int64})
}
if state == "cancelled" {
cancelledSteps = append(cancelledSteps, step)
}
}
if err == nil {
err = rows.Err()
}
rows.Close()
if err != nil {
return err
}
result := response{"run_id": id, "status": status, "applied": applied, "cancelled_step_ids": cancelledSteps, "worker_stop_grace_ms": 1000}
if receipt != nil {
result["run_status"], result["status"] = status, "applied"
bindCanvasAIReceipt(result, receipt)
}
encoded, _ := json.Marshal(result)
_, err = tx.ExecContext(r.Context(), `INSERT INTO canvas_ai_mutations(project,workspace_id,run_id,account_id,action,idempotency_key,payload_hash,response_body) VALUES($1,$2,$3,$4,'cancel',$5,$6,$7)`, project, workspace, id, account, key, hash, encoded)
if err != nil {
return err
}
return commitCanvasAIReceipt(w, r, tx, project, workspace, account, receipt, 200, "applied", result)
}

Some files were not shown because too many files have changed in this diff Show More