Compare commits
132 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 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 | |||
| 81c2d2e6df | |||
| d80854deae | |||
| 9e5d805f5a | |||
| 4d5e6e2512 | |||
| cc8ddba7aa | |||
| c7ec5f7eb2 | |||
| 33719a549b | |||
| 17cec9ff06 | |||
| 4e5832c14b |
@@ -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
|
||||
@@ -0,0 +1,29 @@
|
||||
name: Deploy Rust Bedrock
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
concurrency:
|
||||
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: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Build the Rust release
|
||||
run: bash deploy/build-release.sh
|
||||
- name: Publish and initialize Bedrock storage
|
||||
env:
|
||||
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/release.sh target/bedrock-release/bedrock "$GITHUB_SHA"
|
||||
+3
-2
@@ -1,2 +1,3 @@
|
||||
.env
|
||||
/bin/
|
||||
/target
|
||||
/bedrock.sqlite3
|
||||
/bedrock.sqlite3-*
|
||||
|
||||
Generated
+2123
File diff suppressed because it is too large
Load Diff
+37
@@ -0,0 +1,37 @@
|
||||
[workspace]
|
||||
members = ["crates/*"]
|
||||
resolver = "3"
|
||||
|
||||
[workspace.package]
|
||||
edition = "2024"
|
||||
rust-version = "1.91"
|
||||
|
||||
[workspace.dependencies]
|
||||
clusters = { path = "crates/clusters" }
|
||||
db = { path = "crates/db" }
|
||||
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"
|
||||
tempfile = "3"
|
||||
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"
|
||||
|
||||
[package]
|
||||
name = "bedrock"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
db.workspace = true
|
||||
serde_json.workspace = true
|
||||
tokio.workspace = true
|
||||
@@ -1,24 +1,36 @@
|
||||
# 造物工坊 · 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 `db` 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 构建并检查。部署时运行 `foundry` 二进制,通过 HTTPS 反向代理转发至服务监听地址。通过 `GET /healthz` 检查进程,通过 `GET /readyz` 检查认证库。
|
||||
5. 代理避免记录 Google 回调的查询参数及认证请求头。设置入口限流,并定时删除三张临时表(`oauth_attempts`、`login_grants`、`project_sessions`)中 `expires_at <= now()` 的记录。
|
||||
`db` owns the transactional document data, revisions, and snapshots used by the application. `clusters` resolves deployment settings. The `db` connection module selects the SQL driver and read endpoints. The backend modules share the connection pools and transaction implementation in `common.rs`.
|
||||
|
||||
## 前端接入
|
||||
Notion describes sharding online PostgreSQL block data by workspace and feeding a downstream S3 data lake from PostgreSQL changes. Bedrock currently supports selecting a configured SQL cluster and using its read replicas. Workspace sharding, S3 object storage, 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)
|
||||
|
||||
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` 撤销会话并清理本地凭证。刷新页面后,内存凭证需要通过重新登录获取。
|
||||
## Database configuration
|
||||
|
||||
同一个 Google 账号首次进入不同项目时,会分别创建用户 ID。会话绑定其签发项目。Google 账号的标识 `sub` 用于认领同一项目的既有账号,邮箱只作为资料字段。当前注册模式为开放注册。
|
||||
Set `BEDROCK_DB_CONFIG` to the path of a private JSON deployment configuration to select a different cluster. For example:
|
||||
|
||||
## 验收
|
||||
```json
|
||||
{
|
||||
"deployment": "production",
|
||||
"cluster": "east",
|
||||
"clusters": {
|
||||
"east": {
|
||||
"driver": "postgres",
|
||||
"primary": "postgres://bedrock@primary.example.net/bedrock",
|
||||
"replicas": ["postgres://bedrock_reader@replica.example.net/bedrock"],
|
||||
"max_connections": 5
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
用同一个 Google 测试账号分别登录两个项目,确认用户 ID 不同。用 A 的会话请求 B 的 `me` 应返回 401。验证兑换码重放被拒绝,并确认退出 A 后 B 的会话仍有效。
|
||||
The database must already exist for PostgreSQL and MySQL. Bedrock creates its own tables and deployment row on a writable startup. Network endpoints use TLS with certificate and hostname verification by default. For a private test database without TLS, set the cluster's `tls` to `"disabled"`. A top-level `"read_only": true` opens an existing deployment without initializing it. A SQLite deployment can set `sqlite_path` to use another file.
|
||||
|
||||
Applications connect with `db::connect`. 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.
|
||||
|
||||
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.
|
||||
|
||||
See [deployment configuration](deploy/README.md) for the PostgreSQL configuration renderer and deployment-only variables.
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
# 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.
|
||||
|
||||

|
||||
@@ -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)"
|
||||
/tmp/bedrock-target/debug/bedrock
|
||||
test -f bedrock.sqlite3
|
||||
'
|
||||
@@ -1,54 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"gitea.entroia.com/Zayden-Jung/foundry-core/internal/auth"
|
||||
"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() {
|
||||
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)
|
||||
}
|
||||
server := &http.Server{
|
||||
Addr: net.JoinHostPort(env("HOST", "127.0.0.1"), env("PORT", "8080")),
|
||||
Handler: handler, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second,
|
||||
WriteTimeout: 30 * time.Second, IdleTimeout: 60 * time.Second,
|
||||
}
|
||||
log.Fatal(server.ListenAndServe())
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "clusters"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde.workspace = true
|
||||
thiserror.workspace = true
|
||||
url.workspace = true
|
||||
@@ -0,0 +1,229 @@
|
||||
use std::{collections::BTreeMap, fmt, path::Path};
|
||||
|
||||
use serde::Deserialize;
|
||||
use thiserror::Error;
|
||||
use url::Url;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Driver {
|
||||
#[default]
|
||||
Sqlite,
|
||||
Postgres,
|
||||
Mysql,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Tls {
|
||||
#[default]
|
||||
VerifyFull,
|
||||
Disabled,
|
||||
}
|
||||
|
||||
/// A database address. Debug output includes the full value, which may contain credentials.
|
||||
#[derive(Clone, Deserialize)]
|
||||
#[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
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Cluster {
|
||||
pub driver: Driver,
|
||||
pub primary: Address,
|
||||
#[serde(default)]
|
||||
pub replicas: Vec<Address>,
|
||||
#[serde(default)]
|
||||
pub tls: Tls,
|
||||
#[serde(default = "default_pool_size")]
|
||||
pub max_connections: u32,
|
||||
}
|
||||
|
||||
const fn default_pool_size() -> u32 {
|
||||
5
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct DeploymentConfig {
|
||||
pub deployment: String,
|
||||
pub cluster: Option<String>,
|
||||
pub clusters: BTreeMap<String, Cluster>,
|
||||
pub read_only: bool,
|
||||
pub sqlite_path: Address,
|
||||
}
|
||||
|
||||
impl Default for DeploymentConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
deployment: "default".into(),
|
||||
cluster: None,
|
||||
clusters: BTreeMap::new(),
|
||||
read_only: false,
|
||||
sqlite_path: "bedrock.sqlite3".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ResolvedDeployment {
|
||||
pub deployment: String,
|
||||
pub cluster: Option<String>,
|
||||
pub driver: Driver,
|
||||
pub primary: Address,
|
||||
pub replicas: Vec<Address>,
|
||||
pub read_only: bool,
|
||||
pub max_connections: u32,
|
||||
}
|
||||
|
||||
#[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("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),
|
||||
}
|
||||
|
||||
impl DeploymentConfig {
|
||||
pub fn resolve(&self) -> Result<ResolvedDeployment, ConfigError> {
|
||||
validate_name(&self.deployment, "deployment")?;
|
||||
let local = Cluster {
|
||||
driver: Driver::Sqlite,
|
||||
primary: self.sqlite_path.clone(),
|
||||
replicas: vec![],
|
||||
tls: Tls::Disabled,
|
||||
max_connections: 1,
|
||||
};
|
||||
let cluster = match &self.cluster {
|
||||
Some(name) => {
|
||||
validate_name(name, "cluster")?;
|
||||
self.clusters.get(name).ok_or(ConfigError::UnknownCluster)?
|
||||
}
|
||||
None if self.clusters.is_empty() => &local,
|
||||
None => return Err(ConfigError::ClusterRequired),
|
||||
};
|
||||
if cluster.max_connections == 0 {
|
||||
return Err(ConfigError::PoolSize);
|
||||
}
|
||||
if cluster.driver == Driver::Sqlite && !cluster.replicas.is_empty() {
|
||||
return Err(ConfigError::SqliteReplicas);
|
||||
}
|
||||
let primary = resolve_address(cluster, &cluster.primary, self.read_only)?;
|
||||
let replicas = cluster
|
||||
.replicas
|
||||
.iter()
|
||||
.map(|address| resolve_address(cluster, address, true))
|
||||
.collect::<Result<_, _>>()?;
|
||||
Ok(ResolvedDeployment {
|
||||
deployment: self.deployment.clone(),
|
||||
cluster: self.cluster.clone(),
|
||||
driver: cluster.driver,
|
||||
primary,
|
||||
replicas,
|
||||
read_only: self.read_only,
|
||||
max_connections: cluster.max_connections,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
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(())
|
||||
}
|
||||
|
||||
fn resolve_address(
|
||||
cluster: &Cluster,
|
||||
address: &Address,
|
||||
read_only: bool,
|
||||
) -> Result<Address, ConfigError> {
|
||||
let address = address.connection_string();
|
||||
let (driver, tls_key, tls_enabled, tls_disabled) = match cluster.driver {
|
||||
Driver::Sqlite => return sqlite_url(address, read_only),
|
||||
Driver::Postgres => ("postgres", "sslmode", "verify-full", "disable"),
|
||||
Driver::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(url.into()))
|
||||
}
|
||||
|
||||
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(format!("sqlite:{file}?mode={mode}")))
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use clusters::{Address, Cluster, ConfigError, DeploymentConfig, Driver, 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 {
|
||||
cluster: Some("regional".into()),
|
||||
clusters: BTreeMap::from([(
|
||||
"regional".into(),
|
||||
Cluster {
|
||||
driver: Driver::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();
|
||||
assert!(
|
||||
resolved
|
||||
.primary
|
||||
.connection_string()
|
||||
.ends_with("sslmode=verify-full")
|
||||
);
|
||||
assert!(
|
||||
resolved.replicas[0]
|
||||
.connection_string()
|
||||
.ends_with("sslmode=verify-full")
|
||||
);
|
||||
config.clusters.get_mut("regional").unwrap().replicas[0] =
|
||||
"mysql://user:secret@replica/bedrock".into();
|
||||
assert!(matches!(
|
||||
config.resolve(),
|
||||
Err(ConfigError::Url("postgres"))
|
||||
));
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
[package]
|
||||
name = "db"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
clusters.workspace = true
|
||||
deadpool-postgres.workspace = true
|
||||
mysql_async.workspace = true
|
||||
rusqlite.workspace = true
|
||||
rustls.workspace = true
|
||||
rustls-pemfile.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,169 @@
|
||||
//! 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("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,200 @@
|
||||
//! Deployment bootstrap and read routing.
|
||||
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use clusters::{Address, ConfigError, DeploymentConfig, Driver, ResolvedDeployment};
|
||||
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(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> {
|
||||
let config = config.resolve()?;
|
||||
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: &ResolvedDeployment, 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,14 @@
|
||||
//! Bedrock's transactional document storage for SQL databases.
|
||||
|
||||
mod common;
|
||||
mod connection;
|
||||
pub mod mysql;
|
||||
pub mod postgres;
|
||||
pub mod sqlite;
|
||||
|
||||
pub use clusters::Driver as Dialect;
|
||||
pub use clusters::{Address, Cluster, ConfigError, DeploymentConfig, 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};
|
||||
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,285 @@
|
||||
use std::{collections::BTreeMap, env, time::Duration};
|
||||
|
||||
use db::{
|
||||
Cluster, Connection, DeploymentConfig, Driver, Mutation, ReadPreference, 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(),
|
||||
cluster: Some("test".into()),
|
||||
clusters: BTreeMap::from([(
|
||||
"test".into(),
|
||||
Cluster {
|
||||
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 = DeploymentConfig {
|
||||
sqlite_path: filename.to_str().unwrap().into(),
|
||||
..DeploymentConfig::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 config = DeploymentConfig {
|
||||
read_only: true,
|
||||
sqlite_path: filename.to_str().unwrap().into(),
|
||||
..DeploymentConfig::default()
|
||||
};
|
||||
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");
|
||||
config
|
||||
.clusters
|
||||
.get_mut("test")
|
||||
.unwrap()
|
||||
.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
|
||||
);
|
||||
}
|
||||
@@ -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,17 @@
|
||||
# Deployment configuration
|
||||
|
||||
Deployments pass the path of a JSON configuration file to the Bedrock executable using `BEDROCK_DB_CONFIG`. The Rust libraries accept structured configuration.
|
||||
|
||||
- **SQLite** uses `deploy/sqlite.json` as a template. Set `sqlite_path` to a persistent, writable volume path.
|
||||
- **PostgreSQL** injects the Gitea Actions variable values `BEDROCK_PG_HOST`, `BEDROCK_PG_PORT`, `BEDROCK_PG_DATABASE` and `BEDROCK_PG_USER`, and the secret `BEDROCK_PG_PASSWORD`, into the deployment step. Run `python3 deploy/render-postgres.py /path/to/private/bedrock.json --deployment production`. The renderer writes a private file and does not print its contents. Mount that file for the Bedrock service and set `BEDROCK_DB_CONFIG` to the mounted path. The configured database must already exist and the server must present a trusted certificate matching the database address.
|
||||
- **MySQL** accepts the same cluster shape described in the [storage configuration](../README.md) with `"driver": "mysql"` and a `mysql://` endpoint.
|
||||
|
||||
Keep `BEDROCK_S3_SECRET_KEY`, `BEDROCK_S3_ENDPOINT`, and `BEDROCK_S3_ACCESS_KEY` scoped to the deployment that consumes object storage. S3 integration is pending. The PostgreSQL renderer and `db` use only SQL configuration.
|
||||
|
||||
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.
|
||||
|
||||
## Release on the existing deployment host
|
||||
|
||||
Gitea builds a release on `ces-control` when a commit lands on `main`. The deploy step renders the private PostgreSQL configuration and runs the current one-shot Rust storage initializer 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.
|
||||
|
||||

|
||||
@@ -0,0 +1,105 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1160" height="1000" viewBox="0 0 1160 1000" role="img" aria-labelledby="title description">
|
||||
<title id="title">Bedrock 的部署与手动验证流程</title>
|
||||
<desc id="description">main 提交触发 Gitea CD。release.sh 调用配置渲染器并启动临时容器。容器内 Rust Bedrock 初始化已有 PostgreSQL 数据库中的 Bedrock 表。另有独立手动检查路径。</desc>
|
||||
<defs>
|
||||
<marker id="arrow" viewBox="0 0 9 9" refX="8" refY="4.5" markerWidth="9" markerHeight="9" orient="auto" markerUnits="userSpaceOnUse"><path d="M0 0 9 4.5 0 9z" fill="#557866"/></marker>
|
||||
<marker id="arrow-red" viewBox="0 0 9 9" refX="8" refY="4.5" markerWidth="9" markerHeight="9" orient="auto" markerUnits="userSpaceOnUse"><path d="M0 0 9 4.5 0 9z" fill="#976752"/></marker>
|
||||
<pattern id="grid" width="16" height="16" patternUnits="userSpaceOnUse"><circle cx="2" cy="2" r=".7" fill="#a4b2a3" opacity=".28"/></pattern>
|
||||
</defs>
|
||||
<style>
|
||||
text{font-family:-apple-system,BlinkMacSystemFont,"PingFang SC","Hiragino Sans GB","Microsoft YaHei",sans-serif;fill:#1e3328}
|
||||
.title{font-size:37px;font-weight:720;letter-spacing:-.4px}
|
||||
.kicker,.code{font-family:ui-monospace,"SF Mono",Consolas,monospace}
|
||||
.kicker{font-size:13px;letter-spacing:2px;font-weight:650;fill:#426251}
|
||||
.lane{font-size:23px;font-weight:700}
|
||||
.headline,.code{font-size:17px;font-weight:700}
|
||||
.detail{font-size:14px;fill:#475d50}
|
||||
.badge{font-size:14px;font-weight:650;fill:#325541}
|
||||
.result{font-size:15px;font-weight:700;fill:#38624b}
|
||||
.failed{fill:#8b5642}
|
||||
.flow{fill:none;stroke:#557866;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round;marker-end:url(#arrow)}
|
||||
.flow-fail{fill:none;stroke:#976752;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round;marker-end:url(#arrow-red)}
|
||||
.side{stroke-dasharray:4 4}
|
||||
</style>
|
||||
<rect width="1160" height="1000" rx="23" fill="#f8f8f1"/>
|
||||
<rect x=".5" y=".5" width="1159" height="999" rx="22.5" fill="none" stroke="#d9dfd3"/>
|
||||
<path d="M34 103H1126" stroke="#d9dfd3"/>
|
||||
<rect x="34" y="123" width="738" height="842" rx="17" fill="#eef2e9" stroke="#d9e1d5"/>
|
||||
<rect x="34" y="123" width="738" height="842" rx="17" fill="url(#grid)"/>
|
||||
<rect x="792" y="123" width="334" height="842" rx="17" fill="#f1f1e9" stroke="#dfe1d6"/>
|
||||
|
||||
<text x="34" y="36" class="kicker">BEDROCK / DEPLOYMENT</text>
|
||||
<text x="34" y="81" class="title">Bedrock 的部署与手动验证流程</text>
|
||||
<text x="55" y="159" class="lane">CD · 原部署机</text>
|
||||
<text x="813" y="159" class="lane">手动验证</text>
|
||||
<path d="M310 215 V235" class="flow"/>
|
||||
<path d="M310 298 V318" class="flow"/>
|
||||
<path d="M310 381 V414" class="flow"/>
|
||||
<path d="M310 477 V497" class="flow"/>
|
||||
<path d="M310 560 V580" class="flow"/>
|
||||
<path d="M310 643 V663" class="flow"/>
|
||||
<path d="M310 740 V821" class="flow"/>
|
||||
<path d="M564 447 H536" class="flow side"/>
|
||||
<path d="M310 896 V906 H224 V919" class="flow"/>
|
||||
<path d="M310 896 V906 H568 V919" class="flow-fail"/>
|
||||
<path d="M959 215 V235" class="flow"/>
|
||||
<path d="M959 298 V318" class="flow"/>
|
||||
<path d="M959 396 V416" class="flow"/>
|
||||
<path d="M959 494 V522" class="flow"/>
|
||||
<rect x="84" y="171" width="452" height="44" rx="9" fill="#e0eee0" stroke="#8eaf98"/>
|
||||
<path d="M93 183v20" stroke="#8bac94" stroke-width="2" stroke-linecap="round"/>
|
||||
<text x="104" y="199.0" class="headline">main 收到提交</text>
|
||||
<rect x="84" y="235" width="452" height="63" rx="9" fill="#fbfbf6" stroke="#bfcec0"/>
|
||||
<text x="104" y="264" class="code">deploy.yml</text>
|
||||
<text x="104" y="285" class="detail">Gitea 在 ces-control 上检出代码并编排部署。</text>
|
||||
<rect x="84" y="318" width="452" height="63" rx="9" fill="#fbfbf6" stroke="#bfcec0"/>
|
||||
<text x="104" y="347" class="code">build-release.sh</text>
|
||||
<text x="104" y="368" class="detail">在 Rust 容器内编译 release,输出 Bedrock 二进制。</text>
|
||||
<text x="327" y="402" class="detail">二进制路径与 Git SHA 交给发布脚本</text>
|
||||
<rect x="84" y="414" width="452" height="63" rx="9" fill="#fbfbf6" stroke="#bfcec0"/>
|
||||
<text x="104" y="443" class="code">release.sh</text>
|
||||
<text x="104" y="464" class="detail">建立暂存目录,放入二进制。</text>
|
||||
<rect x="564" y="412" width="185" height="70" rx="9" fill="#edf1e8" stroke="#c1ccbf"/>
|
||||
<text x="584" y="441" class="headline">Gitea 部署配置</text>
|
||||
<text x="584" y="462" class="detail">PostgreSQL Variables</text>
|
||||
<text x="584" y="481" class="detail">和密码 Secret</text>
|
||||
<rect x="84" y="497" width="452" height="63" rx="9" fill="#fbfbf6" stroke="#bfcec0"/>
|
||||
<text x="104" y="526" class="code">render-postgres.py</text>
|
||||
<text x="104" y="547" class="detail">由 release.sh 调用,生成权限为 0600 的 bedrock.json。</text>
|
||||
<rect x="84" y="580" width="452" height="63" rx="9" fill="#fbfbf6" stroke="#bfcec0"/>
|
||||
<text x="104" y="609" class="headline">release.sh 启动临时容器</text>
|
||||
<text x="104" y="630" class="detail">挂载二进制和配置,运行 Rust bedrock。</text>
|
||||
<rect x="84" y="663" width="452" height="77" rx="9" fill="#e0eee0" stroke="#8eaf98"/>
|
||||
<path d="M93 675v53" stroke="#8bac94" stroke-width="2" stroke-linecap="round"/>
|
||||
<text x="104" y="692" class="headline">Rust Bedrock 读取配置</text>
|
||||
<text x="104" y="713" class="detail">通过 db::connect 选择 postgres。</text>
|
||||
<text x="104" y="732" class="detail">配置由 BEDROCK_DB_CONFIG 指定。</text>
|
||||
<rect x="84" y="821" width="452" height="75" rx="9" fill="#e0eee0" stroke="#8eaf98"/>
|
||||
<text x="104" y="847" class="headline">在已有 PostgreSQL 数据库内初始化</text>
|
||||
<text x="104" y="869" class="detail">postgres.rs 提供 SQL,common.rs 在事务里执行。</text>
|
||||
<text x="104" y="887" class="detail">创建 Bedrock 表并登记 production 部署。</text>
|
||||
<text x="328" y="787" class="detail">进入 Store::initialize()</text>
|
||||
<text x="118" y="909" class="result">成功</text>
|
||||
<text x="614" y="909" class="result failed">失败</text>
|
||||
<rect x="84" y="919" width="280" height="32" rx="9" fill="#e0eee0" stroke="#8eaf98"/>
|
||||
<path d="M93 931v8" stroke="#8bac94" stroke-width="2" stroke-linecap="round"/>
|
||||
<text x="104" y="941.0" class="headline">保存版本并切换 current</text>
|
||||
<rect x="401" y="919" width="348" height="32" rx="9" fill="#f7eee6" stroke="#d4b7a6"/>
|
||||
<text x="421" y="941.0" class="headline">清理暂存目录,保留上一版 current</text>
|
||||
<rect x="813" y="171" width="292" height="44" rx="9" fill="#fbfbf6" stroke="#bfcec0"/>
|
||||
<text x="833" y="199.0" class="headline">手动运行</text>
|
||||
<rect x="813" y="235" width="292" height="63" rx="9" fill="#fbfbf6" stroke="#bfcec0"/>
|
||||
<text x="833" y="264" class="code">ci/check-sql.sh</text>
|
||||
<text x="833" y="285" class="detail">脚本独立于部署工作流。</text>
|
||||
<rect x="813" y="318" width="292" height="78" rx="9" fill="#fbfbf6" stroke="#bfcec0"/>
|
||||
<text x="833" y="347" class="headline">准备隔离环境</text>
|
||||
<text x="833" y="368" class="detail">启动临时 PostgreSQL 和 MySQL。</text>
|
||||
<text x="833" y="387" class="detail">SQLite 使用临时本地文件。</text>
|
||||
<rect x="813" y="416" width="292" height="78" rx="9" fill="#fbfbf6" stroke="#bfcec0"/>
|
||||
<text x="833" y="445" class="headline">运行三库检查</text>
|
||||
<text x="833" y="466" class="detail">执行格式检查、测试、构建,</text>
|
||||
<text x="833" y="485" class="detail">验证 SQLite 默认启动。</text>
|
||||
<rect x="813" y="522" width="292" height="63" rx="9" fill="#edf1e8" stroke="#c1ccbf"/>
|
||||
<text x="833" y="551" class="headline">退出时清理</text>
|
||||
<text x="833" y="572" class="detail">删除测试容器和临时网络。</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 7.4 KiB |
@@ -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 --bin bedrock
|
||||
install -m 755 /tmp/bedrock-target/release/bedrock /out/bedrock
|
||||
'
|
||||
@@ -0,0 +1,49 @@
|
||||
#!/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"
|
||||
python3 "$(dirname "$0")/render-postgres.py" "$stage/bedrock.json" --deployment production
|
||||
|
||||
# The current binary is a one-shot storage initializer. It publishes no ports.
|
||||
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.json \
|
||||
debian:bookworm-slim /release/bedrock
|
||||
|
||||
release="$revision.${stage##*.}"
|
||||
# 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,74 @@
|
||||
#!/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")
|
||||
options = parser.parse_args()
|
||||
if not re.fullmatch(r"[A-Za-z0-9._-]{1,128}", options.deployment):
|
||||
parser.error("invalid deployment name")
|
||||
config = {
|
||||
"deployment": options.deployment,
|
||||
"cluster": "postgres",
|
||||
"clusters": {
|
||||
"postgres": {
|
||||
"driver": "postgres",
|
||||
"primary": database_url(),
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
# Write with owner-only permissions, then replace the destination atomically.
|
||||
file = tempfile.NamedTemporaryFile(mode="w", dir=options.output.parent, delete=False)
|
||||
try:
|
||||
with file:
|
||||
json.dump(config, file, indent=2)
|
||||
file.write("\n")
|
||||
os.replace(file.name, options.output)
|
||||
finally:
|
||||
Path(file.name).unlink(missing_ok=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"deployment": "default",
|
||||
"sqlite_path": "bedrock.sqlite3"
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
use std::{env, error::Error, fs};
|
||||
|
||||
use db::{DeploymentConfig, connect};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn Error>> {
|
||||
let config = match env::var_os("BEDROCK_DB_CONFIG") {
|
||||
Some(path) => serde_json::from_slice::<DeploymentConfig>(&fs::read(path)?)?,
|
||||
None => DeploymentConfig::default(),
|
||||
};
|
||||
let db = connect(&config).await?;
|
||||
println!(
|
||||
"Bedrock storage ready ({:?}, revision {}, read-only: {})",
|
||||
db.driver(),
|
||||
db.revision().await?,
|
||||
db.is_read_only()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user