Compare commits
149 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| dd8b41b67e | |||
| f0470c406b | |||
| af9f25baa5 | |||
| 66be7099ec | |||
| 1775943d79 | |||
| 01023404be | |||
| df2fff7a80 | |||
| 3eebf55112 | |||
| 1b10181cf1 | |||
| 66b6910eb1 | |||
| 8707eb87b6 | |||
| 455a3580d6 | |||
| 69513d9ffb | |||
| 9869a9966c | |||
| 6469d3aad6 | |||
| 365be3870e | |||
| ac62c8a655 | |||
| 296fb9b1b7 | |||
| 3c551ca0a3 | |||
| deb535c256 | |||
| 353ea1558c | |||
| b64a88011f | |||
| 3d0ce4ad7d | |||
| 73192bf944 | |||
| 51beaafc4c | |||
| 7982fffcda | |||
| c270adbab4 | |||
| 9f3848199d | |||
| 698f126033 | |||
| c98b694a70 | |||
| 6c51e68817 | |||
| 81b70f0046 | |||
| 6b34a11dbb | |||
| 36184b07a0 | |||
| bb15a7043c | |||
| 2f2a39621c | |||
| 55d66d5d9b | |||
| d31cd5615e | |||
| 351cc156dd | |||
| a01bac3a48 | |||
| 632c3a8882 | |||
| 807a02e081 | |||
| 0c34703ec7 | |||
| 59f2ef1bf2 | |||
| fa79b1e6ce | |||
| 6fcfbf1def | |||
| 3bc3051383 | |||
| 53bc8d73eb | |||
| 00fd89af1a | |||
| 27412f58af | |||
| 1090591503 | |||
| 30829eeb86 | |||
| 506f778ac3 | |||
| 36d69133b8 | |||
| 5db2bf3c98 | |||
| 3268c57bc6 | |||
| d00388504c | |||
| cc3068ace3 | |||
| 1605b5a9d6 | |||
| ca01ea3ea1 | |||
| 8395baa24f | |||
| daec39ead4 | |||
| 121ce7496c | |||
| c8f3940d26 | |||
| da6a5f8207 | |||
| 6131fb5d7b | |||
| 28ca98a506 | |||
| 95812c3a96 | |||
| efa916060a | |||
| cc2ca05cd4 | |||
| be2014cc31 | |||
| 6b07c19728 | |||
| 6a0a2e1912 | |||
| 7d7408a0ec | |||
| ee04a6372b | |||
| d6e877712a | |||
| 6d1a5b5c83 | |||
| 9cf6e4cedf | |||
| ad6ab30b5f | |||
| 789edcc61b | |||
| e38254821a | |||
| ff88865e91 | |||
| fb1bf4ab85 | |||
| ca90b3fea3 | |||
| 31258b995f | |||
| 24b27dcac4 | |||
| d6690c3764 | |||
| c9bb38454d | |||
| 2d4aefbdc0 | |||
| 56b6181598 | |||
| cdf48f1691 | |||
| f12c4ad8bd | |||
| 00ff738705 | |||
| fa76773efc | |||
| 0d7fc4dbe5 | |||
| bf8763e0de | |||
| 4a89137e38 | |||
| b7499e3815 | |||
| 12458e10dc | |||
| b85e8bd2ca | |||
| 19884b2a90 | |||
| 9f01aa3db8 | |||
| 026ee22c1e | |||
| 142c7b2d86 | |||
| 9dd166d5de | |||
| 1363792bb0 | |||
| 913bf4292b | |||
| 028e453d92 | |||
| 81cf7d9448 | |||
| 2207c85ca6 | |||
| 09c78d3ab8 | |||
| b2ae48e250 | |||
| 8abc79dc5b | |||
| 67765c17f4 | |||
| 630ed42d53 | |||
| 07fd678cf3 | |||
| 7e1bd538c1 | |||
| 56cd0c5715 | |||
| b4e537b4ad | |||
| d6ee8942f1 | |||
| 7847167043 | |||
| 867f0303d8 | |||
| 460b05f187 | |||
| 34c461a61c | |||
| 022086beb8 | |||
| 6f504ebe15 | |||
| 57aab71d45 | |||
| 6f36ef27bb | |||
| e8ed5e4f9f | |||
| b1e0d783e6 | |||
| 4043c89520 | |||
| 155ce28c37 | |||
| 6c69fcbaaa | |||
| 5b9af931c7 | |||
| 9d5ab9e215 | |||
| f69575d48f | |||
| fbe0910638 | |||
| 5c0ad30a7a | |||
| 206cd45098 | |||
| 4a06944fec | |||
| e0ba9c08e8 | |||
| bfcea1b3af | |||
| 0d0521f13d | |||
| 1b756d36ce | |||
| 53c4dbee8e | |||
| e626a2359e | |||
| 0fd84f0f6e | |||
| c30a3cd197 | |||
| 08aa0d69b6 |
@@ -1,7 +0,0 @@
|
||||
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
|
||||
FOUNDRY_PROJECTS='{"notes":"http://localhost:3000/auth/callback","board":"http://localhost:3001/auth/callback"}'
|
||||
HOST=127.0.0.1
|
||||
PORT=8080
|
||||
@@ -1,35 +0,0 @@
|
||||
name: Foundry Go checks
|
||||
on: [push, pull_request]
|
||||
|
||||
jobs:
|
||||
check:
|
||||
runs-on: ces-control
|
||||
timeout-minutes: 10
|
||||
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
|
||||
- name: Smoke test HTTP routes
|
||||
env:
|
||||
PUBLIC_ORIGIN: https://api.example.com
|
||||
DATABASE_URL: postgres://foundry:fixture@127.0.0.1:5432/foundry
|
||||
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
-24
@@ -1,39 +1,29 @@
|
||||
name: Deploy Foundry Core
|
||||
name: Deploy Rust Bedrock
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- 'cmd/**'
|
||||
- 'internal/**'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- 'deploy/**'
|
||||
- '.gitea/workflows/deploy.yml'
|
||||
|
||||
concurrency:
|
||||
group: foundry-core-main-deploy
|
||||
group: bedrock-rust-deploy
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
if: gitea.ref == 'refs/heads/main' && gitea.event_name == 'push'
|
||||
runs-on: ces-control
|
||||
timeout-minutes: 15
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache: false
|
||||
- name: Verify and build
|
||||
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
|
||||
- name: Deploy and verify backend readiness
|
||||
persist-credentials: false
|
||||
- name: Build the Rust release
|
||||
run: bash deploy/gitea/build-release.sh
|
||||
- name: Publish and initialize Bedrock storage
|
||||
env:
|
||||
GOOGLE_CLIENT_ID: ${{ secrets.GOOGLE_CLIENT_ID }}
|
||||
GOOGLE_CLIENT_SECRET: ${{ secrets.GOOGLE_CLIENT_SECRET }}
|
||||
FOUNDRY_PROJECTS: ${{ vars.FOUNDRY_PROJECTS }}
|
||||
run: bash deploy/release.sh bin/foundry
|
||||
BEDROCK_PG_HOST: ${{ vars.BEDROCK_PG_HOST }}
|
||||
BEDROCK_PG_PORT: ${{ vars.BEDROCK_PG_PORT }}
|
||||
BEDROCK_PG_DATABASE: ${{ vars.BEDROCK_PG_DATABASE }}
|
||||
BEDROCK_PG_USER: ${{ vars.BEDROCK_PG_USER }}
|
||||
BEDROCK_PG_PASSWORD: ${{ secrets.BEDROCK_PG_PASSWORD }}
|
||||
run: bash deploy/gitea/release.sh target/bedrock-release/bedrock "$GITHUB_SHA"
|
||||
|
||||
+3
-2
@@ -1,2 +1,3 @@
|
||||
.env
|
||||
/bin/
|
||||
/target
|
||||
/bedrock.sqlite3
|
||||
/bedrock.sqlite3-*
|
||||
|
||||
Generated
+2512
File diff suppressed because it is too large
Load Diff
+31
@@ -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"
|
||||
@@ -1,63 +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 同意页面的应用名称。
|
||||
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()` 的记录。
|
||||
`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`.
|
||||
|
||||
## Actions 部署配置
|
||||
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)
|
||||
|
||||
在仓库的 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 在启动容器时注入。
|
||||
## Web backend
|
||||
|
||||
Google OAuth 的授权回调地址为 `https://api.foundry.entroia.com/auth/google/callback`。工作流会验证数据库就绪、匿名请求返回 401 和 HTTPS 就绪。前端接入后,可在浏览器用 Google 测试账号验证完整登录、回调、兑换和会话。
|
||||
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.
|
||||
|
||||
## 前端接入
|
||||
| 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` |
|
||||
|
||||
1. 在浏览器用 Web Crypto 生成 32 字节随机值,编码为无填充 Base64URL,作为 verifier 暂存在当前 tab 的 sessionStorage。对 verifier 字符串做 SHA-256 并用相同编码得到 challenge。
|
||||
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` 撤销会话并清理本地凭证。刷新页面后,内存凭证需要通过重新登录获取。
|
||||
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.
|
||||
|
||||
同一个 Google 账号首次进入不同项目时,会分别创建用户 ID。会话绑定其签发项目。Google 账号的标识 `sub` 用于认领同一项目的既有账号,邮箱只作为资料字段。当前注册模式为开放注册。
|
||||
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.
|
||||
|
||||
## 验收
|
||||
## Database configuration
|
||||
|
||||
用同一个 Google 测试账号分别登录两个项目,确认用户 ID 不同。用 A 的会话请求 B 的 `me` 应返回 401。验证兑换码重放被拒绝,并确认退出 A 后 B 的会话仍有效。
|
||||
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.
|
||||
|
||||
## Codex execution
|
||||
`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.
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
On the deployment host, provision `/opt/endoleap-infra/foundry/codex` with:
|
||||
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.
|
||||
|
||||
- `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.
|
||||
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.
|
||||
|
||||
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. To replace an existing worker, stop and remove
|
||||
its container, then run `bash deploy/codex-worker.sh /absolute/path/to/foundry`
|
||||
with the desired ces-control build. 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.
|
||||
See [deployment configuration](deploy/README.md) for the PostgreSQL configuration renderer and deployment-only variables.
|
||||
|
||||
@@ -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["清理测试容器和临时网络"]
|
||||
```
|
||||
@@ -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
|
||||
'
|
||||
@@ -1,63 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"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"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/stdlib"
|
||||
)
|
||||
|
||||
func env(key, fallback string) string {
|
||||
if value := os.Getenv(key); value != "" {
|
||||
return value
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func main() {
|
||||
if len(os.Args) == 2 && os.Args[1] == "codex-worker" {
|
||||
log.Fatal(codex.ServeWorker("/run/foundry-codex/worker.sock"))
|
||||
}
|
||||
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")
|
||||
}
|
||||
db := stdlib.OpenDB(*config)
|
||||
defer db.Close()
|
||||
handler, err := auth.New(db, callbacks, origin.ResolveReference(&url.URL{Path: "/auth/google/callback"}).String(), id, secret)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
if err := codex.Register(mux, callbacks, os.Getenv("FOUNDRY_CODEX_SOCKET"), os.Getenv("FOUNDRY_CODEX_GRANTS")); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
mux.Handle("/", handler)
|
||||
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())
|
||||
}
|
||||
@@ -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
|
||||
@@ -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()))
|
||||
}
|
||||
@@ -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"] }
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
|
||||
```
|
||||
@@ -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(())
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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),
|
||||
}
|
||||
@@ -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>,
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -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),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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}")))
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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)));
|
||||
}
|
||||
@@ -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
|
||||
@@ -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";
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
@@ -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};
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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),
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
));
|
||||
}
|
||||
@@ -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
|
||||
@@ -0,0 +1,4 @@
|
||||
/// Produces a textual description from already available data.
|
||||
pub trait Contextualize {
|
||||
fn render_context(&self) -> String;
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -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};
|
||||
@@ -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()
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
));
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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["清理测试容器和临时网络"]
|
||||
```
|
||||
@@ -1,23 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
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"
|
||||
install -d -m 700 -o 1000 -g 1000 "$dir/run"
|
||||
|
||||
# The host operator supplies an isolated Codex home and starts a single worker.
|
||||
# The Docker default bridge supplies egress independently of Foundry's network.
|
||||
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 384m --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" \
|
||||
node:24-bookworm-slim /opt/foundry codex-worker
|
||||
@@ -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
|
||||
'
|
||||
@@ -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"
|
||||
@@ -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()
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,10 @@
|
||||
deployment: default
|
||||
config_version: local
|
||||
resources:
|
||||
local:
|
||||
kind: sql
|
||||
driver: sqlite
|
||||
primary: bedrock.sqlite3
|
||||
max_connections: 1
|
||||
bindings:
|
||||
documents: local
|
||||
@@ -1,113 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
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.
|
||||
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"
|
||||
docker network inspect "$network" >/dev/null
|
||||
|
||||
release=$(mktemp -d "$foundry/release.XXXXXXXX")
|
||||
install -m 755 "$1" "$release/foundry"
|
||||
export HOST=0.0.0.0 PORT=8080 PUBLIC_ORIGIN="$origin"
|
||||
codex_mounts=()
|
||||
codex_dir=$foundry/codex
|
||||
if [[ -d "$codex_dir" ]]; then
|
||||
if ! docker inspect -f '{{.State.Running}}' foundry-codex-worker 2>/dev/null | grep -qx true; then
|
||||
bash "$(dirname "$0")/codex-worker.sh" "$release/foundry" >/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
|
||||
|
||||
docker run -d --name "$candidate" "${codex_mounts[@]}" --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 \
|
||||
--user 1000:1000 --cap-drop ALL --security-opt no-new-privileges \
|
||||
--read-only --memory 128m \
|
||||
--mount "type=bind,source=$release/foundry,target=/opt/foundry,readonly" \
|
||||
node:24-bookworm-slim /opt/foundry >/dev/null
|
||||
|
||||
cleanup_candidate() {
|
||||
docker rm -f "${live:-$candidate}" >/dev/null 2>&1 || true
|
||||
}
|
||||
trap cleanup_candidate EXIT
|
||||
|
||||
docker exec "$candidate" node -e '
|
||||
const assert = require("node:assert/strict");
|
||||
async function verify() {
|
||||
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=$(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'
|
||||
@@ -1,80 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
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
|
||||
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
|
||||
rollback() {
|
||||
if [[ -s "$backup" ]]; then
|
||||
cp "$backup" "$edge/.restore"
|
||||
mv "$edge/.restore" "$route"
|
||||
else
|
||||
rm -f "$route"
|
||||
fi
|
||||
rm -f "$backup"
|
||||
}
|
||||
trap rollback EXIT
|
||||
|
||||
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"
|
||||
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
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
@@ -1,14 +0,0 @@
|
||||
module gitea.entroia.com/Zayden-Jung/foundry-core
|
||||
|
||||
go 1.25.0
|
||||
|
||||
require github.com/jackc/pgx/v5 v5.7.6
|
||||
|
||||
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
|
||||
)
|
||||
@@ -1,28 +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/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=
|
||||
@@ -1,329 +0,0 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var projectName = regexp.MustCompile(`^[a-z][a-z0-9-]*$`)
|
||||
var tokenPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{43}$`)
|
||||
|
||||
type service struct {
|
||||
db *sql.DB
|
||||
projects map[string]*url.URL
|
||||
redirectURI, clientID, secret string
|
||||
google *http.Client
|
||||
}
|
||||
|
||||
func New(db *sql.DB, callbacks map[string]string, redirectURI, id, secret string) (http.Handler, error) {
|
||||
s := &service{db: db, 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 }}}
|
||||
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
|
||||
}
|
||||
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("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
|
||||
}
|
||||
|
||||
type payload map[string]any
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
func reject(w http.ResponseWriter, status int, code string) error {
|
||||
reply(w, status, payload{"error": code})
|
||||
return nil
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func token() string {
|
||||
var value [32]byte
|
||||
rand.Read(value[:])
|
||||
return base64.RawURLEncoding.EncodeToString(value[:])
|
||||
}
|
||||
|
||||
func digest(value string) string {
|
||||
sum := sha256.Sum256([]byte(value))
|
||||
return base64.RawURLEncoding.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
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 == "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)
|
||||
}
|
||||
switch {
|
||||
case r.Method == http.MethodOptions:
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Authorization, X-Foundry-Code, X-Foundry-Verifier")
|
||||
reply(w, 204, nil)
|
||||
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
|
||||
}
|
||||
|
||||
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}
|
||||
}
|
||||
|
||||
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 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"}, "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
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
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()
|
||||
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))
|
||||
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"`
|
||||
}
|
||||
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 := token()
|
||||
_, err = s.db.ExecContext(ctx, `
|
||||
WITH account AS (
|
||||
INSERT INTO project_accounts (project, id, google_subject, email) VALUES ($1, gen_random_uuid(), $2, $3)
|
||||
ON CONFLICT (project, google_subject) DO UPDATE SET email = EXCLUDED.email
|
||||
RETURNING id
|
||||
)
|
||||
INSERT INTO login_grants
|
||||
SELECT $4, $1, id, $5, now() + interval '1 minute' FROM account
|
||||
`, project, user.Subject, user.Email, digest(grant), challenge)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
destination.Fragment = "code=" + grant
|
||||
http.Redirect(w, r, destination.String(), 302)
|
||||
return nil
|
||||
}
|
||||
|
||||
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 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
|
||||
SELECT $4, $2, account_id, now() + interval '8 hours' FROM 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": 28800})
|
||||
return nil
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
var id string
|
||||
var email *string
|
||||
err := s.db.QueryRowContext(r.Context(), `
|
||||
SELECT a.id::text, a.email FROM project_sessions s
|
||||
JOIN project_accounts a ON a.project = s.project AND a.id = s.account_id
|
||||
WHERE s.token_hash = $1 AND s.project = $2 AND s.expires_at > now()
|
||||
`, digest(token), project).Scan(&id, &email)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return reject(w, 401, "invalid_session")
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
reply(w, 200, payload{"project": project, "id": id, "email": email})
|
||||
return nil
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
package codex
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
maxRequest = 32 << 10
|
||||
maxOutput = 512 << 10
|
||||
timeout = 90 * time.Second
|
||||
)
|
||||
|
||||
type task struct {
|
||||
Prompt string `json:"prompt"`
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
func fail(w http.ResponseWriter, status int, code string) {
|
||||
writeJSON(w, status, map[string]string{"error": code})
|
||||
}
|
||||
|
||||
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.
|
||||
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
|
||||
}
|
||||
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
|
||||
}
|
||||
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()
|
||||
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
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
package codex
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
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 := &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")
|
||||
}
|
||||
@@ -1,134 +0,0 @@
|
||||
package codex
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
const executable = "/opt/codex/node_modules/.bin/codex"
|
||||
|
||||
var errOutputLimit = errors.New("Codex output limit exceeded")
|
||||
|
||||
type outputBuffer struct {
|
||||
buffer bytes.Buffer
|
||||
exceeded bool
|
||||
}
|
||||
|
||||
func (b *outputBuffer) Write(p []byte) (int, error) {
|
||||
if len(p) > maxOutput-b.buffer.Len() {
|
||||
b.exceeded = true
|
||||
return 0, errOutputLimit
|
||||
}
|
||||
return b.buffer.Write(p)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
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)
|
||||
}
|
||||
})
|
||||
server := &http.Server{Handler: mux, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: timeout + 15*time.Second}
|
||||
return server.Serve(listener)
|
||||
}
|
||||
|
||||
func execute(w http.ResponseWriter, r *http.Request, prompt 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", "-")
|
||||
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)
|
||||
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))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user