chadtmiller.com/group-host
atmosphere group host
0
0
Tests reach the reference PDS and PLC, on the space alpha in CI
.knotless/workflows/test.yml+45−2
| @@ -1,6 +1,13 @@ | ||
# The tests, under `just cov`'s gate: every test binary, failing under 100% | ||
# of lines or functions. A binary the tests start (the host, the command) | ||
# is counted as it runs, so it is told to stop rather than killed. | ||
# | ||
# The tests that reach the network run against the reference PDS and PLC | ||
# (harness/pds.mjs), on the space alpha built at ATPROTO_COMMIT, as | ||
# knotless's test.yml builds it: the same commit, so the host and knotless | ||
# are held to the same alpha. Node, the harness's packages, the alpha's | ||
# build, cargo-llvm-cov and the build are kept between runs; each is made | ||
# again only when what it is made from changes. | ||
image: rust:1.98 | ||
# A pre-flight, as check is: the merge queue takes a pull into a batch only | ||
# once this has passed at its head. | ||
| @@ -8,12 +15,48 @@ queue: first | ||
on: | ||
push: {refs: [refs/heads/main]} | ||
pull: {base: [refs/heads/main, refs/heads/feature/*]} | ||
cache: [target, /usr/local/cargo/registry, /usr/local/rustup, /opt/tools] | ||
cache: [target, /usr/local/cargo/registry, /usr/local/rustup, /opt/tools, /opt/node, /opt/atproto, harness/node_modules] | ||
env: | ||
# The space alpha the tests run against. | ||
ATPROTO_COMMIT: 11c5d98cd50261c5e1201fedc5c6c05a7b8d1ccf | ||
# Bumped when the steps that build the alpha change, to build it again. | ||
ALPHA_BUILD: "2" | ||
steps: | ||
- uses: chadtmiller.com/steps/node@1 | ||
with: {version: 24.22.1} | ||
- uses: chadtmiller.com/steps/npm-ci@1 | ||
name: harness | ||
with: {dir: harness, omit: dev} | ||
- uses: chadtmiller.com/steps/cargo-llvm-cov@1 | ||
with: {version: 0.9.1} | ||
- name: spaces alpha | ||
run: | | ||
[ "$(cat /opt/atproto/.built 2>/dev/null)" = "$ATPROTO_COMMIT $ALPHA_BUILD" ] && exit 0 | ||
export PATH=/opt/node/bin:$PATH COREPACK_ENABLE_DOWNLOAD_PROMPT=0 COREPACK_HOME=/opt/atproto/.corepack | ||
find /opt/atproto -mindepth 1 -delete | ||
cd /opt/atproto | ||
git init -q . && git fetch -q --depth 1 https://github.com/bluesky-social/atproto.git "$ATPROTO_COMMIT" && git checkout -q FETCH_HEAD | ||
mkdir .bin && corepack enable --install-directory /opt/atproto/.bin | ||
export PATH=/opt/atproto/.bin:$PATH | ||
pnpm install --frozen-lockfile --ignore-scripts | ||
pnpm run build:tooling --force | ||
pnpm --filter '@atproto/dev-env^...' --filter @atproto/dev-env run --if-present prebuild | ||
pnpm exec tsc --build packages/dev-env/tsconfig.build.json | ||
# The PDS serves its OAuth sign-in pages from this bundle, and will | ||
# not start without it. | ||
pnpm --filter @atproto/oauth-provider-ui run build:ui | ||
echo "$ATPROTO_COMMIT $ALPHA_BUILD" > /opt/atproto/.built | ||
- name: sqlite | ||
run: | | ||
# SQLite's native module for the alpha's PDS, which the install above | ||
# skips building, and the harness's own for the stock PDS. | ||
export PATH=/opt/node/bin:$PATH | ||
for from in /opt/atproto/packages/pds harness; do | ||
dir="$(dirname "$(node -p "require.resolve('better-sqlite3/package.json', { paths: ['$from'] })")")" | ||
[ -f "$dir/build/Release/better_sqlite3.node" ] || (cd "$dir" && npm run install) | ||
done | ||
- name: test | ||
run: | | ||
export PATH=/opt/tools:$PATH | ||
export PATH=/opt/node/bin:/opt/tools:$PATH GROUP_HOST_DEV_ENV=/opt/atproto/packages/dev-env | ||
cargo llvm-cov --workspace --ignore-filename-regex '(tests/|harness/)' \ | ||
--fail-under-lines 100 --fail-under-functions 100 --show-missing-lines | ||
crates/group-host/tests/common/mod.rs+2−0
| @@ -3,6 +3,8 @@ | ||
| ||
#![allow(dead_code)] | ||
| ||
pub mod net; | ||
| ||
use atproto::plc::Signed; | ||
use axum::extract::{Path, State}; | ||
use axum::http::StatusCode; | ||
crates/group-host/tests/common/net.rsnew+58−0
| @@ -0,0 +1,58 @@ | ||
//! The reference network (`harness/pds.mjs`): a PLC directory and the | ||
//! reference PDS, on the space alpha where `GROUP_HOST_DEV_ENV` names its | ||
//! build, started once for a test binary and stopped as it exits. | ||
| ||
use serde::Deserialize; | ||
use std::io::{BufRead, BufReader}; | ||
use std::path::Path; | ||
use std::process::{Child, Command, Stdio}; | ||
use std::sync::{Mutex, OnceLock}; | ||
| ||
#[derive(Deserialize, Clone, Debug)] | ||
pub struct Net { | ||
pub pds: String, | ||
pub plc: String, | ||
/// Whether the PDS is on the space alpha. | ||
pub spaces: bool, | ||
pub accounts: Vec<Member>, | ||
} | ||
| ||
/// An account on the reference PDS. | ||
#[derive(Deserialize, Clone, Debug)] | ||
pub struct Member { | ||
pub handle: String, | ||
pub did: String, | ||
pub password: String, | ||
} | ||
| ||
static NET: OnceLock<Net> = OnceLock::new(); | ||
/// Kept so the harness lives as long as the tests; its stdin closes, and | ||
/// it stops, when this process exits. | ||
static CHILD: Mutex<Option<Child>> = Mutex::new(None); | ||
| ||
pub fn net() -> &'static Net { | ||
NET.get_or_init(|| { | ||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); | ||
let mut child = Command::new("node") | ||
.arg(root.join("harness/pds.mjs")) | ||
.args(["--accounts", "alice,bob"]) | ||
.stdin(Stdio::piped()) | ||
.stdout(Stdio::piped()) | ||
.stderr(Stdio::inherit()) | ||
.spawn() | ||
.expect("node runs harness/pds.mjs (npm ci in harness/)"); | ||
let mut lines = BufReader::new(child.stdout.take().unwrap()).lines(); | ||
let net: Net = loop { | ||
let line = lines | ||
.next() | ||
.expect("the harness reports before it stops") | ||
.unwrap(); | ||
if line.starts_with("{\"pds\"") { | ||
break serde_json::from_str(&line).unwrap(); | ||
} | ||
}; | ||
std::thread::spawn(move || for _ in lines {}); | ||
*CHILD.lock().unwrap() = Some(child); | ||
net | ||
}) | ||
} | ||
crates/group-host/tests/interop.rsnew+88−0
| @@ -0,0 +1,88 @@ | ||
//! The host against the reference network (`harness/pds.mjs`): a real PLC | ||
//! directory, and on the space alpha, a real member's PDS. | ||
| ||
mod common; | ||
| ||
use atproto::did; | ||
use atproto::space_auth::{Expect, Kind, space_host_aud, verify}; | ||
use common::net::net; | ||
use common::start; | ||
use serde_json::{Value, json}; | ||
| ||
#[tokio::test] | ||
async fn a_group_on_the_reference_network() { | ||
let net = net(); | ||
let h = start(&[("PLC_URL", net.plc.as_str())], false).await; | ||
let group = h.host.create_account("riders.groups.test").await.unwrap(); | ||
| ||
// The reference directory took the group's genesis, signed with the | ||
// host's rotation key, and serves its document. | ||
let http = reqwest::Client::new(); | ||
let doc: Value = http | ||
.get(format!("{}/{group}", net.plc)) | ||
.send() | ||
.await | ||
.unwrap() | ||
.json() | ||
.await | ||
.unwrap(); | ||
assert_eq!(did::pds(&doc).as_deref(), Some("https://host.test")); | ||
assert_eq!(did::handle(&doc).as_deref(), Some("riders.groups.test")); | ||
let account = h.host.store.account(&group).unwrap().unwrap(); | ||
assert_eq!(did::signing_key(&doc).unwrap(), account.signing.public()); | ||
if !net.spaces { | ||
eprintln!("the reference PDS has no spaces: GROUP_HOST_DEV_ENV names the alpha's build"); | ||
return; | ||
} | ||
| ||
// A member asks their own PDS for a delegation token to the group's | ||
// members space, and the token is as the host will check it. | ||
let alice = &net.accounts[0]; | ||
let session: Value = http | ||
.post(format!("{}/xrpc/com.atproto.server.createSession", net.pds)) | ||
.json(&json!({"identifier": alice.handle, "password": alice.password})) | ||
.send() | ||
.await | ||
.unwrap() | ||
.json() | ||
.await | ||
.unwrap(); | ||
let space = format!("at://{group}/space/fyi.opensocial.members/self"); | ||
let res = http | ||
.get(format!( | ||
"{}/xrpc/com.atproto.space.getDelegationToken", | ||
net.pds | ||
)) | ||
.query(&[("space", space.as_str())]) | ||
.bearer_auth(session["accessJwt"].as_str().unwrap()) | ||
.send() | ||
.await | ||
.unwrap(); | ||
let status = res.status(); | ||
let body: Value = res.json().await.unwrap(); | ||
assert!(status.is_success(), "{status} {body}"); | ||
let theirs: Value = http | ||
.get(format!("{}/{}", net.plc, alice.did)) | ||
.send() | ||
.await | ||
.unwrap() | ||
.json() | ||
.await | ||
.unwrap(); | ||
let key = did::signing_key(&theirs).unwrap(); | ||
let now = group_host::time::now_millis() as u64 / 1000; | ||
let aud = space_host_aud(&group); | ||
let expect = Expect { | ||
aud: Some(&aud), | ||
sub: Some(&space), | ||
}; | ||
let token = verify( | ||
Kind::Delegation, | ||
body["token"].as_str().unwrap(), | ||
&key, | ||
&expect, | ||
now, | ||
) | ||
.unwrap(); | ||
assert_eq!(token.iss, alice.did); | ||
} | ||
crates/group-host/Cargo.toml+1−0
| @@ -19,6 +19,7 @@ tracing.workspace = true | ||
tracing-subscriber.workspace = true | ||
| ||
[dev-dependencies] | ||
serde.workspace = true | ||
tempfile.workspace = true | ||
tokio-tungstenite.workspace = true | ||
futures.workspace = true | ||
docs/development.md+8−0
| @@ -12,6 +12,14 @@ just web-dev # the console, asking that host | ||
| ||
## Tests | ||
| ||
The tests that reach the network run against the reference PDS and a PLC | ||
directory, which `harness/pds.mjs` starts once for each test binary that | ||
asks (`tests/common/net.rs`), on Node at the version `.node-version` names. | ||
On npm's PDS, which has no spaces, the tests of a space skip what needs | ||
one; CI runs them on the space alpha, built at the commit | ||
`.knotless/workflows/test.yml` names, and `GROUP_HOST_DEV_ENV` names such a | ||
build (an atproto checkout's `packages/dev-env`) to run them here. | ||
| ||
`just test` runs every test; `just t <cargo test args>` a selection; | ||
`just cov` all of them under the gate the `test` check holds: 100% of | ||
lines and functions, tests and the harness left out. A test that starts | ||
harness/package-lock.jsonnew+9487−0
A large diff, not shown.
harness/package.json+7−1
| @@ -2,5 +2,11 @@ | ||
"name": "group-host-harness", | ||
"private": true, | ||
"type": "module", | ||
"description": "The checks run beside the tests: the web components' layers and the lexicons" | ||
"description": "The checks beside the tests, and the reference PDS and PLC the host's tests run against (pds.mjs)", | ||
"dependencies": { | ||
"@atproto/dev-env": "0.6.26" | ||
}, | ||
"devDependencies": { | ||
"@playwright/test": "1.58.2" | ||
} | ||
} | ||
harness/pds.mjsnew+84−0
| @@ -0,0 +1,84 @@ | ||
// Runs the reference PDS (@atproto/pds, through @atproto/dev-env) and a PLC | ||
// directory on free ports, makes test accounts, prints one JSON line naming | ||
// them, and stops when stdin closes. As knotless's harness/pds.mjs, less what | ||
// only knotless needs. | ||
// | ||
// node harness/pds.mjs [--accounts alice,bob] | ||
// | ||
// GROUP_HOST_DEV_ENV names a built dev-env package to run instead of the npm | ||
// one: an atproto checkout's packages/dev-env on the spaces alpha, as CI | ||
// builds it (.knotless/workflows/test.yml). The alpha's PDS migrates an | ||
// account's database each time it opens it; here only the first time. | ||
| ||
import { fileURLToPath, pathToFileURL } from 'node:url' | ||
import { dirname, join, resolve } from 'node:path' | ||
import { readFileSync, realpathSync } from 'node:fs' | ||
import { createRequire } from 'node:module' | ||
import { AsyncLocalStorage } from 'node:async_hooks' | ||
| ||
const root = resolve(dirname(fileURLToPath(import.meta.url)), '..') | ||
// The PDS's better-sqlite3 is built for the Node .node-version names. | ||
const pinned = readFileSync(join(root, '.node-version'), 'utf8').trim() | ||
if (process.versions.node.split('.')[0] !== pinned.split('.')[0]) { | ||
console.error(`harness/pds.mjs runs on Node ${pinned}, as .node-version says, not ${process.version}`) | ||
process.exit(1) | ||
} | ||
const devEnv = process.env.GROUP_HOST_DEV_ENV | ||
const { TestNetworkNoAppView } = await import( | ||
devEnv ? pathToFileURL(resolve(root, devEnv, 'dist/index.js')).href : '@atproto/dev-env' | ||
) | ||
if (devEnv) await migrateOnce(resolve(root, devEnv)) | ||
| ||
/// Has the dev-env's PDS migrate each account's database on its first | ||
/// opening alone, rather than on every one. | ||
async function migrateOnce(dir) { | ||
const index = createRequire(join(dir, 'package.json')).resolve('@atproto/pds') | ||
const dist = dirname(realpathSync(index)) | ||
const load = (file) => import(pathToFileURL(join(dist, file)).href) | ||
const { ActorStore } = await load('actor-store/actor-store.js') | ||
const { Migrator } = await load('db/migrator.js') | ||
const opened = new Set() | ||
const again = new AsyncLocalStorage() | ||
const open = ActorStore.prototype.openDb | ||
ActorStore.prototype.openDb = async function (did) { | ||
const { dbLocation } = await this.getLocation(did) | ||
const db = await again.run(opened.has(dbLocation), () => open.call(this, did)) | ||
opened.add(dbLocation) | ||
return db | ||
} | ||
const migrate = Migrator.prototype.migrateToLatestOrThrow | ||
Migrator.prototype.migrateToLatestOrThrow = function () { | ||
return again.getStore() ? Promise.resolve([]) : migrate.call(this) | ||
} | ||
} | ||
| ||
const at = process.argv.indexOf('--accounts') | ||
const names = (at === -1 ? 'alice,bob' : process.argv[at + 1]).split(',') | ||
| ||
const net = await TestNetworkNoAppView.create({ pds: { hostname: 'localhost' } }) | ||
| ||
const accounts = [] | ||
for (const name of names) { | ||
const password = `${name}-password` | ||
const res = await fetch(`${net.pds.url}/xrpc/com.atproto.server.createAccount`, { | ||
method: 'POST', | ||
headers: { 'content-type': 'application/json' }, | ||
body: JSON.stringify({ email: `${name}@test.com`, handle: `${name}.test`, password }), | ||
}) | ||
if (!res.ok) throw new Error(`createAccount ${name}: ${await res.text()}`) | ||
const { did, handle } = await res.json() | ||
accounts.push({ handle, did, password }) | ||
} | ||
| ||
const described = await fetch(`${net.pds.url}/xrpc/com.atproto.server.describeServer`).then((r) => r.json()) | ||
console.log(JSON.stringify({ pds: net.pds.url, plc: net.plc.url, spaces: described.spacesAlpha === true, accounts })) | ||
| ||
const shutdown = async () => { | ||
await net.close() | ||
process.exit(0) | ||
} | ||
process.stdin.on('end', shutdown) | ||
process.stdin.on('close', shutdown) | ||
process.stdin.resume() | ||
process.on('SIGTERM', shutdown) | ||
process.on('SIGINT', shutdown) | ||
Justfile+3−1
| @@ -5,9 +5,11 @@ toolchain := `dirname "$(rustup which --toolchain stable cargo)"` | ||
cargo := "env PATH='" + toolchain + ":" + env_var('PATH') + "' rustup run stable cargo" | ||
ignore := "(tests/|harness/)" | ||
| ||
# Install the web pages' packages and coverage tools. | ||
# Install the web pages' packages, the harness's (the reference PDS the | ||
# tests reach the network through), and coverage tools. | ||
setup: | ||
cd web && npm install --no-audit --no-fund | ||
cd harness && npm ci --no-audit --no-fund | ||
rustup component add llvm-tools-preview --toolchain stable | ||
command -v cargo-llvm-cov >/dev/null || cargo install cargo-llvm-cov | ||
| ||