Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fe7ecbffc9 | ||
|
|
4102b52f8e | ||
|
|
2336b000fc | ||
|
|
c31a0e8e5c | ||
|
|
2fa5b9de67 | ||
|
|
4241782f92 | ||
|
|
824259dc7c | ||
|
|
e056e1487e | ||
|
|
ca3fff0f44 | ||
|
|
1ce3c2bb97 | ||
|
|
48436538f1 | ||
|
|
8f494679b8 |
No files matched your search
+14
-13
@@ -2,7 +2,8 @@ name: CI
|
|||||||
|
|
||||||
on:
|
on:
|
||||||
pull_request:
|
pull_request:
|
||||||
types: [opened, synchronize, reopened, labeled, unlabeled]
|
branches: [main]
|
||||||
|
types: [opened, synchronize, reopened]
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
inputs:
|
inputs:
|
||||||
validation_level:
|
validation_level:
|
||||||
@@ -17,9 +18,6 @@ on:
|
|||||||
options: [none, production]
|
options: [none, production]
|
||||||
default: none
|
default: none
|
||||||
required: true
|
required: true
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- main
|
|
||||||
|
|
||||||
env:
|
env:
|
||||||
CARGO_BUILD_JOBS: "2"
|
CARGO_BUILD_JOBS: "2"
|
||||||
@@ -46,7 +44,7 @@ jobs:
|
|||||||
GITEA_EVENT_NAME: ${{ gitea.event_name }}
|
GITEA_EVENT_NAME: ${{ gitea.event_name }}
|
||||||
GITEA_EVENT_BEFORE: ${{ gitea.event.before }}
|
GITEA_EVENT_BEFORE: ${{ gitea.event.before }}
|
||||||
GITEA_PR_BASE_SHA: ${{ gitea.event.pull_request.base.sha }}
|
GITEA_PR_BASE_SHA: ${{ gitea.event.pull_request.base.sha }}
|
||||||
FORCE_FULL: ${{ inputs.validation_level == 'feature' || contains(gitea.event.pull_request.labels.*.name, 'feature-ready') }}
|
FORCE_FULL: ${{ gitea.event_name == 'pull_request' || inputs.validation_level == 'feature' }}
|
||||||
run: python3 scripts/ci-release-tooling-scope.py
|
run: python3 scripts/ci-release-tooling-scope.py
|
||||||
|
|
||||||
- name: Install Rust toolchain
|
- name: Install Rust toolchain
|
||||||
@@ -187,8 +185,7 @@ jobs:
|
|||||||
needs: rust
|
needs: rust
|
||||||
name: Rust Feature Validation
|
name: Rust Feature Validation
|
||||||
if: >-
|
if: >-
|
||||||
inputs.validation_level == 'feature' ||
|
gitea.event_name == 'pull_request' || inputs.validation_level == 'feature'
|
||||||
contains(gitea.event.pull_request.labels.*.name, 'feature-ready')
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
@@ -251,8 +248,7 @@ jobs:
|
|||||||
frontend-e2e:
|
frontend-e2e:
|
||||||
needs: [rust, ui]
|
needs: [rust, ui]
|
||||||
if: >-
|
if: >-
|
||||||
inputs.validation_level == 'feature' ||
|
gitea.event_name == 'pull_request' || inputs.validation_level == 'feature'
|
||||||
contains(gitea.event.pull_request.labels.*.name, 'feature-ready')
|
|
||||||
name: Frontend E2E
|
name: Frontend E2E
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
services:
|
services:
|
||||||
@@ -323,7 +319,13 @@ jobs:
|
|||||||
run: npx playwright install --with-deps chromium
|
run: npx playwright install --with-deps chromium
|
||||||
|
|
||||||
- name: Prebuild e2e services
|
- name: Prebuild e2e services
|
||||||
run: cargo build -p admin-api -p mcp-server --jobs "$CARGO_BUILD_JOBS"
|
env:
|
||||||
|
SQLX_OFFLINE: "true"
|
||||||
|
# Match playwright-stack.sh so Cargo reuses these artifacts during startup.
|
||||||
|
run: |
|
||||||
|
cargo build -p admin-api --bin crank-migrate --jobs "$CARGO_BUILD_JOBS"
|
||||||
|
cargo build -p admin-api --bin admin-api --example e2e_storage_counts --jobs "$CARGO_BUILD_JOBS"
|
||||||
|
cargo build -p mcp-server --jobs "$CARGO_BUILD_JOBS"
|
||||||
|
|
||||||
- name: Run Playwright e2e
|
- name: Run Playwright e2e
|
||||||
working-directory: apps/ui
|
working-directory: apps/ui
|
||||||
@@ -361,8 +363,7 @@ jobs:
|
|||||||
deployment:
|
deployment:
|
||||||
needs: [rust, ui]
|
needs: [rust, ui]
|
||||||
if: >-
|
if: >-
|
||||||
inputs.validation_level == 'feature' ||
|
gitea.event_name == 'pull_request' || inputs.validation_level == 'feature'
|
||||||
contains(gitea.event.pull_request.labels.*.name, 'feature-ready')
|
|
||||||
name: Community Image Smoke
|
name: Community Image Smoke
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
@@ -496,7 +497,7 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Require story gates and mode-appropriate feature gates
|
- name: Require story gates and mode-appropriate feature gates
|
||||||
env:
|
env:
|
||||||
FEATURE_VALIDATION: ${{ inputs.validation_level == 'feature' || contains(gitea.event.pull_request.labels.*.name, 'feature-ready') }}
|
FEATURE_VALIDATION: ${{ gitea.event_name == 'pull_request' || inputs.validation_level == 'feature' }}
|
||||||
RUST_RESULT: ${{ needs.rust.result }}
|
RUST_RESULT: ${{ needs.rust.result }}
|
||||||
UI_RESULT: ${{ needs.ui.result }}
|
UI_RESULT: ${{ needs.ui.result }}
|
||||||
RUST_FEATURE_RESULT: ${{ needs.rust-feature.result }}
|
RUST_FEATURE_RESULT: ${{ needs.rust-feature.result }}
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
name: Targeted Frontend Diagnostic
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
env:
|
||||||
|
CARGO_BUILD_JOBS: "2"
|
||||||
|
CARGO_INCREMENTAL: "0"
|
||||||
|
CARGO_PROFILE_DEV_DEBUG: "0"
|
||||||
|
TESTCONTAINERS_RYUK_DISABLED: "true"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
duplicate-submit:
|
||||||
|
name: Duplicate Submit Diagnostic
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 30
|
||||||
|
services:
|
||||||
|
crank-e2e-postgres:
|
||||||
|
image: postgres:16-alpine
|
||||||
|
env:
|
||||||
|
POSTGRES_DB: crank
|
||||||
|
POSTGRES_USER: crank
|
||||||
|
POSTGRES_PASSWORD: crank
|
||||||
|
options: >-
|
||||||
|
--health-cmd "pg_isready -U crank -d crank"
|
||||||
|
--health-interval 10s
|
||||||
|
--health-timeout 5s
|
||||||
|
--health-retries 5
|
||||||
|
env:
|
||||||
|
CRANK_E2E_USE_EXTERNAL_POSTGRES: "1"
|
||||||
|
CRANK_E2E_POSTGRES_HOST: crank-e2e-postgres
|
||||||
|
CRANK_E2E_POSTGRES_PORT: "5432"
|
||||||
|
CRANK_E2E_POSTGRES_DB: crank
|
||||||
|
CRANK_E2E_POSTGRES_USER: crank
|
||||||
|
CRANK_E2E_POSTGRES_PASSWORD: crank
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
- name: Install Rust toolchain
|
||||||
|
run: |
|
||||||
|
set -eu
|
||||||
|
toolchain="$(sed -n 's/^channel = "\(.*\)"/\1/p' rust-toolchain.toml | head -n1)"
|
||||||
|
if [ -z "$toolchain" ]; then
|
||||||
|
echo "Unable to read Rust toolchain channel from rust-toolchain.toml" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
if ! rustup run "$toolchain" rustc --version >/dev/null 2>&1 || \
|
||||||
|
! rustup run "$toolchain" cargo --version >/dev/null 2>&1 || \
|
||||||
|
! rustup run "$toolchain" rustfmt --version >/dev/null 2>&1 || \
|
||||||
|
! rustup run "$toolchain" cargo-clippy --version >/dev/null 2>&1; then
|
||||||
|
rustup toolchain install "$toolchain" --profile minimal --component clippy --component rustfmt
|
||||||
|
fi
|
||||||
|
host="$(rustup run "$toolchain" rustc -vV | sed -n 's/^host: //p')"
|
||||||
|
toolchain_dir="${RUSTUP_HOME:-$HOME/.rustup}/toolchains/${toolchain}-${host}"
|
||||||
|
toolchain_bin="$toolchain_dir/bin"
|
||||||
|
if [ ! -x "$toolchain_bin/rustc" ] || [ ! -x "$toolchain_bin/cargo" ]; then
|
||||||
|
echo "Rust $toolchain was not installed at $toolchain_dir." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
printf '%s\n' "$toolchain_bin" >> "$GITHUB_PATH"
|
||||||
|
"$toolchain_bin/rustc" --version
|
||||||
|
"$toolchain_bin/cargo" --version
|
||||||
|
"$toolchain_bin/rustfmt" --version
|
||||||
|
"$toolchain_bin/cargo-clippy" --version
|
||||||
|
- name: Verify runner tools
|
||||||
|
run: |
|
||||||
|
rustc --version
|
||||||
|
cargo --version
|
||||||
|
node --version
|
||||||
|
npm --version
|
||||||
|
docker --version
|
||||||
|
- name: Install UI dependencies
|
||||||
|
working-directory: apps/ui
|
||||||
|
run: npm ci
|
||||||
|
- name: Install Chromium
|
||||||
|
working-directory: apps/ui
|
||||||
|
run: npx playwright install --with-deps chromium
|
||||||
|
- name: Prebuild E2E services
|
||||||
|
run: cargo build -p admin-api -p mcp-server --jobs "$CARGO_BUILD_JOBS"
|
||||||
|
- name: Run only the duplicate-submit test
|
||||||
|
working-directory: apps/ui
|
||||||
|
env:
|
||||||
|
CI: "1"
|
||||||
|
run: >-
|
||||||
|
npx playwright test tests/e2e/secrets.spec.js
|
||||||
|
--grep "secret modal clears sensitive values and locks duplicate submit while saving"
|
||||||
|
--workers=1
|
||||||
|
--retries=0
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
name: Story CI
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
branches: ['epic/**']
|
||||||
|
types: [opened, synchronize, reopened]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
linters:
|
||||||
|
name: Linters
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Install Rust toolchain
|
||||||
|
run: |
|
||||||
|
set -eu
|
||||||
|
toolchain="$(sed -n 's/^channel = "\(.*\)"/\1/p' rust-toolchain.toml | head -n1)"
|
||||||
|
if [ -z "$toolchain" ]; then
|
||||||
|
echo "Unable to read Rust toolchain channel from rust-toolchain.toml" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
if ! rustup run "$toolchain" rustc --version >/dev/null 2>&1 || \
|
||||||
|
! rustup run "$toolchain" cargo --version >/dev/null 2>&1 || \
|
||||||
|
! rustup run "$toolchain" rustfmt --version >/dev/null 2>&1 || \
|
||||||
|
! rustup run "$toolchain" cargo-clippy --version >/dev/null 2>&1; then
|
||||||
|
rustup toolchain install "$toolchain" --profile minimal --component clippy --component rustfmt
|
||||||
|
fi
|
||||||
|
host="$(rustup run "$toolchain" rustc -vV | sed -n 's/^host: //p')"
|
||||||
|
toolchain_dir="${RUSTUP_HOME:-$HOME/.rustup}/toolchains/${toolchain}-${host}"
|
||||||
|
toolchain_bin="$toolchain_dir/bin"
|
||||||
|
if [ ! -x "$toolchain_bin/rustc" ] || [ ! -x "$toolchain_bin/cargo" ]; then
|
||||||
|
echo "Rust $toolchain was not installed at $toolchain_dir." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
printf '%s\n' "$toolchain_bin" >> "$GITHUB_PATH"
|
||||||
|
"$toolchain_bin/rustc" --version
|
||||||
|
"$toolchain_bin/cargo" --version
|
||||||
|
"$toolchain_bin/rustfmt" --version
|
||||||
|
"$toolchain_bin/cargo-clippy" --version
|
||||||
|
|
||||||
|
- name: Check formatting
|
||||||
|
run: cargo fmt --all --check
|
||||||
|
|
||||||
|
- name: Check Rust code health
|
||||||
|
run: scripts/check-rust-code-health.sh
|
||||||
|
|
||||||
|
- name: Check Rust boundaries
|
||||||
|
run: scripts/check-rust-boundaries.sh
|
||||||
Generated
+8
-8
@@ -598,9 +598,9 @@ checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cookie"
|
name = "cookie"
|
||||||
version = "0.18.1"
|
version = "0.18.3"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747"
|
checksum = "d55f2d6c30eeec7d5c6f98bd4395d4abb1895629eab97ee6522d340623615f8a"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
"time",
|
"time",
|
||||||
@@ -1277,9 +1277,9 @@ checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "form_urlencoded"
|
name = "form_urlencoded"
|
||||||
version = "1.2.2"
|
version = "1.2.3"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
|
checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
]
|
]
|
||||||
@@ -2553,9 +2553,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pin-project-lite"
|
name = "pin-project-lite"
|
||||||
version = "0.2.17"
|
version = "0.2.19"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pkg-config"
|
name = "pkg-config"
|
||||||
@@ -4406,9 +4406,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "url"
|
name = "url"
|
||||||
version = "2.5.8"
|
version = "2.5.9"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
|
checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"form_urlencoded",
|
"form_urlencoded",
|
||||||
"idna",
|
"idna",
|
||||||
|
|||||||
@@ -12,7 +12,9 @@ use crank_observability::{
|
|||||||
MetricService, MetricsConfig, ObservabilityConfig, ObservabilityLifecycle, OtlpTraceConfig,
|
MetricService, MetricsConfig, ObservabilityConfig, ObservabilityLifecycle, OtlpTraceConfig,
|
||||||
RedactionLimits, SentryConfig, ServiceIdentity, bound_metric_service,
|
RedactionLimits, SentryConfig, ServiceIdentity, bound_metric_service,
|
||||||
};
|
};
|
||||||
use crank_registry::{MASTER_KEY_CIPHER_CONTRACT, MasterKeyIdentityCandidate, PostgresRegistry};
|
use crank_registry::{
|
||||||
|
MASTER_KEY_CIPHER_CONTRACT, MasterKeyIdentityCandidate, MigrationAuthority, PostgresRegistry,
|
||||||
|
};
|
||||||
use crank_runtime::SecretCrypto;
|
use crank_runtime::SecretCrypto;
|
||||||
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
|
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
|
||||||
use tower::ServiceExt;
|
use tower::ServiceExt;
|
||||||
@@ -120,12 +122,16 @@ async fn real_admin_startup_runs_immediate_import_maintenance() {
|
|||||||
String::from_utf8_lossy(&applied.stderr)
|
String::from_utf8_lossy(&applied.stderr)
|
||||||
);
|
);
|
||||||
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
|
||||||
|
let canonical_version = MigrationAuthority::sequence()
|
||||||
|
.last()
|
||||||
|
.expect("canonical migration sequence is nonempty")
|
||||||
|
.version;
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
sqlx::query_scalar::<_, Option<i64>>("select max(version) from __crank_migrations")
|
sqlx::query_scalar::<_, Option<i64>>("select max(version) from __crank_migrations")
|
||||||
.fetch_one(&pool)
|
.fetch_one(&pool)
|
||||||
.await
|
.await
|
||||||
.unwrap(),
|
.unwrap(),
|
||||||
Some(23),
|
Some(canonical_version),
|
||||||
"migration binary must install the current canonical ledger",
|
"migration binary must install the current canonical ledger",
|
||||||
);
|
);
|
||||||
sqlx::query(
|
sqlx::query(
|
||||||
|
|||||||
@@ -3,7 +3,8 @@ use std::process::{Command, Output};
|
|||||||
use crank_community_auth::{hash_password, verify_password};
|
use crank_community_auth::{hash_password, verify_password};
|
||||||
use crank_core::{Secret, SecretId, SecretKind, SecretStatus, UserSessionId, WorkspaceId};
|
use crank_core::{Secret, SecretId, SecretKind, SecretStatus, UserSessionId, WorkspaceId};
|
||||||
use crank_registry::{
|
use crank_registry::{
|
||||||
CreateSecretRequest, MASTER_KEY_CIPHER_CONTRACT, MasterKeyIdentityCandidate, PostgresRegistry,
|
CreateSecretRequest, MASTER_KEY_CIPHER_CONTRACT, MasterKeyIdentityCandidate,
|
||||||
|
MigrationAuthority, PostgresRegistry,
|
||||||
};
|
};
|
||||||
use crank_runtime::SecretCrypto;
|
use crank_runtime::SecretCrypto;
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
@@ -40,7 +41,10 @@ fn plan_is_deterministic_and_committed_contract_is_current() {
|
|||||||
);
|
);
|
||||||
assert_eq!(first.stdout, second.stdout);
|
assert_eq!(first.stdout, second.stdout);
|
||||||
let plan: serde_json::Value = serde_json::from_slice(&first.stdout).unwrap();
|
let plan: serde_json::Value = serde_json::from_slice(&first.stdout).unwrap();
|
||||||
assert_eq!(plan["sequence"].as_array().unwrap().len(), 23);
|
assert_eq!(
|
||||||
|
plan["sequence"].as_array().unwrap().len(),
|
||||||
|
MigrationAuthority::sequence().len()
|
||||||
|
);
|
||||||
let target = command(&["plan", "--target-version"], None);
|
let target = command(&["plan", "--target-version"], None);
|
||||||
assert!(
|
assert!(
|
||||||
target.status.success(),
|
target.status.success(),
|
||||||
@@ -104,7 +108,11 @@ async fn database_only_config_can_apply_and_preflight_a_fresh_schema() {
|
|||||||
);
|
);
|
||||||
let result: serde_json::Value = serde_json::from_slice(&preflight.stdout).unwrap();
|
let result: serde_json::Value = serde_json::from_slice(&preflight.stdout).unwrap();
|
||||||
assert_eq!(result["status"], "current");
|
assert_eq!(result["status"], "current");
|
||||||
assert_eq!(result["version"], 23);
|
let canonical_version = MigrationAuthority::sequence()
|
||||||
|
.last()
|
||||||
|
.expect("canonical migration sequence is nonempty")
|
||||||
|
.version;
|
||||||
|
assert_eq!(result["version"].as_i64(), Some(canonical_version));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
|
|||||||
+6
-3
@@ -15,12 +15,15 @@ COPY crank-community.png ./crank-community.png
|
|||||||
|
|
||||||
RUN npm run build
|
RUN npm run build
|
||||||
|
|
||||||
FROM nginx:1.30.6-alpine3.24-slim
|
FROM nginx:1.30.7-alpine3.24-slim
|
||||||
|
|
||||||
RUN apk add --no-cache --upgrade \
|
RUN apk add --no-cache --upgrade \
|
||||||
'pcre2>=10.49-r0' \
|
'pcre2>=10.49-r0' \
|
||||||
'libcrypto3>=3.5.8-r0' \
|
'busybox>=1.37.0-r32' \
|
||||||
'libssl3>=3.5.8-r0'
|
'busybox-binsh>=1.37.0-r32' \
|
||||||
|
'ssl_client>=1.37.0-r32' \
|
||||||
|
'libcrypto3>=3.5.10-r0' \
|
||||||
|
'libssl3>=3.5.10-r0'
|
||||||
|
|
||||||
COPY apps/ui/nginx.conf /etc/nginx/conf.d/default.conf
|
COPY apps/ui/nginx.conf /etc/nginx/conf.d/default.conf
|
||||||
COPY --from=build /app/dist /usr/share/nginx/html
|
COPY --from=build /app/dist /usr/share/nginx/html
|
||||||
|
|||||||
@@ -19,6 +19,11 @@ async function login(page) {
|
|||||||
await page.evaluate(async () => {
|
await page.evaluate(async () => {
|
||||||
await window.CrankAuth.fetchSession(false);
|
await window.CrankAuth.fetchSession(false);
|
||||||
});
|
});
|
||||||
|
await page.waitForFunction(() => Boolean(
|
||||||
|
window.CrankAuth &&
|
||||||
|
typeof window.CrankAuth.getCsrfToken === 'function' &&
|
||||||
|
window.CrankAuth.getCsrfToken()
|
||||||
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
async function browserJson(page, method, urlPath, body, okStatuses = [200]) {
|
async function browserJson(page, method, urlPath, body, okStatuses = [200]) {
|
||||||
|
|||||||
@@ -130,6 +130,33 @@ test('secret modal clears sensitive values and locks duplicate submit while savi
|
|||||||
await page.locator('[data-testid="secret-value-input"]').fill('ui-secret-canary-submit');
|
await page.locator('[data-testid="secret-value-input"]').fill('ui-secret-canary-submit');
|
||||||
const submit = page.locator('[data-testid="secret-submit-button"]');
|
const submit = page.locator('[data-testid="secret-submit-button"]');
|
||||||
await submit.click();
|
await submit.click();
|
||||||
|
const immediate = await page.evaluate(() => {
|
||||||
|
const button = document.querySelector('[data-testid="secret-submit-button"]');
|
||||||
|
const modal = document.querySelector('[data-testid="secret-create-modal"] .modal');
|
||||||
|
return {
|
||||||
|
buttonPresent: Boolean(button),
|
||||||
|
disabled: Boolean(button && button.disabled),
|
||||||
|
labelChanged: Boolean(button && button.textContent.trim() !== 'Create secret'),
|
||||||
|
modalOpen: Boolean(modal && modal.classList.contains('open')),
|
||||||
|
documentReady: document.readyState === 'complete',
|
||||||
|
};
|
||||||
|
});
|
||||||
|
await page.waitForTimeout(250);
|
||||||
|
const afterDelay = await page.evaluate(() => {
|
||||||
|
const button = document.querySelector('[data-testid="secret-submit-button"]');
|
||||||
|
const modal = document.querySelector('[data-testid="secret-create-modal"] .modal');
|
||||||
|
return {
|
||||||
|
buttonPresent: Boolean(button),
|
||||||
|
disabled: Boolean(button && button.disabled),
|
||||||
|
labelChanged: Boolean(button && button.textContent.trim() !== 'Create secret'),
|
||||||
|
modalOpen: Boolean(modal && modal.classList.contains('open')),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
process.stdout.write('[secrets-submit-diagnostic] ' + JSON.stringify({
|
||||||
|
immediate,
|
||||||
|
afterDelay,
|
||||||
|
interceptedCreatePosts: createPosts,
|
||||||
|
}) + '\n');
|
||||||
await expect(submit).toBeDisabled();
|
await expect(submit).toBeDisabled();
|
||||||
await submit.click({ force: true });
|
await submit.click({ force: true });
|
||||||
expect(createPosts).toBe(1);
|
expect(createPosts).toBe(1);
|
||||||
|
|||||||
@@ -46,6 +46,7 @@ mod rmcp_negotiation;
|
|||||||
mod rmcp_notifications;
|
mod rmcp_notifications;
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod rmcp_progress_cancel;
|
mod rmcp_progress_cancel;
|
||||||
|
mod rmcp_progress_peer;
|
||||||
mod rmcp_prompts;
|
mod rmcp_prompts;
|
||||||
mod rmcp_prompts_projection;
|
mod rmcp_prompts_projection;
|
||||||
mod rmcp_resources;
|
mod rmcp_resources;
|
||||||
|
|||||||
@@ -34,8 +34,7 @@ use axum::{
|
|||||||
};
|
};
|
||||||
use crank_core::{CorrelationContext, ExecutionLocale, VerifiedMachineCredential};
|
use crank_core::{CorrelationContext, ExecutionLocale, VerifiedMachineCredential};
|
||||||
use futures_util::stream;
|
use futures_util::stream;
|
||||||
use rmcp::model::{NumberOrString, ProgressNotificationParam};
|
use serde_json::{Number, Value};
|
||||||
use serde_json::{Number, Value, json};
|
|
||||||
use tokio::sync::{mpsc, watch};
|
use tokio::sync::{mpsc, watch};
|
||||||
|
|
||||||
use super::rmcp_dispatch::handle_tools_command;
|
use super::rmcp_dispatch::handle_tools_command;
|
||||||
@@ -83,15 +82,23 @@ impl ProgressToken {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn sdk_token(&self) -> NumberOrString {
|
#[cfg(test)]
|
||||||
|
pub(super) fn sdk_token(&self) -> rmcp::model::NumberOrString {
|
||||||
match self {
|
match self {
|
||||||
Self::Text(text) => NumberOrString::String(text.clone().into()),
|
Self::Text(text) => rmcp::model::NumberOrString::String(text.clone().into()),
|
||||||
Self::Number(number) => number.as_i64().map_or_else(
|
Self::Number(number) => number.as_i64().map_or_else(
|
||||||
|| NumberOrString::String(number.to_string().into()),
|
|| rmcp::model::NumberOrString::String(number.to_string().into()),
|
||||||
NumberOrString::Number,
|
rmcp::model::NumberOrString::Number,
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn raw(&self) -> Value {
|
||||||
|
match self {
|
||||||
|
Self::Text(text) => Value::String(text.clone()),
|
||||||
|
Self::Number(number) => Value::Number(number.clone()),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The progress token of one request parameters object, already validated and bounded. The adapters
|
/// The progress token of one request parameters object, already validated and bounded. The adapters
|
||||||
@@ -133,28 +140,18 @@ pub(crate) struct ProgressEvent {
|
|||||||
message: &'static str,
|
message: &'static str,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The pinned `notifications/progress` frame. Both supported revisions declare the same parameters,
|
#[cfg(test)]
|
||||||
/// so the projection is shared; the token is echoed verbatim and never validated as a credential.
|
impl ProgressEvent {
|
||||||
pub(super) fn progress_frame(token: &ProgressToken, event: &ProgressEvent) -> Value {
|
pub(super) fn sdk_params(
|
||||||
let sdk_params = ProgressNotificationParam::new(
|
&self,
|
||||||
rmcp::model::ProgressToken(token.sdk_token()),
|
token: &ProgressToken,
|
||||||
event.progress as f64,
|
) -> rmcp::model::ProgressNotificationParam {
|
||||||
)
|
rmcp::model::ProgressNotificationParam::new(
|
||||||
.with_message(event.message);
|
rmcp::model::ProgressToken(token.sdk_token()),
|
||||||
let mut params = serde_json::to_value(sdk_params)
|
self.progress as f64,
|
||||||
.expect("finite progress and string/number token are serializable SDK params");
|
)
|
||||||
#[cfg(test)]
|
.with_message(self.message)
|
||||||
super::dispatch_observer::sdk_progress_notification_serialized();
|
|
||||||
// SDK uses i64 tokens and f64 progress; restore the original JSON numbers before wire delivery.
|
|
||||||
if let ProgressToken::Number(number) = token {
|
|
||||||
params["progressToken"] = Value::Number(number.clone());
|
|
||||||
}
|
}
|
||||||
params["progress"] = Value::from(event.progress);
|
|
||||||
json!({
|
|
||||||
"jsonrpc": "2.0",
|
|
||||||
"method": "notifications/progress",
|
|
||||||
"params": params,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
@@ -421,7 +418,8 @@ pub(crate) async fn run_tool_call(
|
|||||||
call,
|
call,
|
||||||
events: progress_events,
|
events: progress_events,
|
||||||
cancel: lifecycle.cancel.clone(),
|
cancel: lifecycle.cancel.clone(),
|
||||||
token,
|
peer: Some(super::rmcp_progress_peer::ProgressPeer::start(token.raw())),
|
||||||
|
outcome: None,
|
||||||
message,
|
message,
|
||||||
protocol_version: protocol_version.clone(),
|
protocol_version: protocol_version.clone(),
|
||||||
pending: VecDeque::new(),
|
pending: VecDeque::new(),
|
||||||
@@ -474,7 +472,8 @@ struct CallStream {
|
|||||||
call: Pin<Box<dyn Future<Output = super::rmcp_tools_runtime::Outcome> + Send>>,
|
call: Pin<Box<dyn Future<Output = super::rmcp_tools_runtime::Outcome> + Send>>,
|
||||||
events: mpsc::Receiver<ProgressEvent>,
|
events: mpsc::Receiver<ProgressEvent>,
|
||||||
cancel: CancelSignal,
|
cancel: CancelSignal,
|
||||||
token: ProgressToken,
|
peer: Option<super::rmcp_progress_peer::ProgressPeer>,
|
||||||
|
outcome: Option<super::rmcp_tools_runtime::Outcome>,
|
||||||
message: Value,
|
message: Value,
|
||||||
protocol_version: String,
|
protocol_version: String,
|
||||||
pending: VecDeque<Event>,
|
pending: VecDeque<Event>,
|
||||||
@@ -511,55 +510,101 @@ async fn next_event_in_scope(
|
|||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
let step = {
|
loop {
|
||||||
let CallStream {
|
let step = if let Some(outcome) = call.outcome.take() {
|
||||||
call,
|
Step::Outcome(outcome)
|
||||||
events,
|
} else {
|
||||||
cancel,
|
let CallStream {
|
||||||
..
|
call,
|
||||||
} = &mut call;
|
events,
|
||||||
tokio::select! {
|
cancel,
|
||||||
biased;
|
..
|
||||||
Some(event) = events.recv() => Step::Progress(event),
|
} = &mut call;
|
||||||
outcome = call => Step::Outcome(outcome),
|
tokio::select! {
|
||||||
_ = cancel.cancelled() => Step::Cancelled,
|
biased;
|
||||||
}
|
Some(event) = events.recv() => Step::Progress(event),
|
||||||
};
|
outcome = call => Step::Outcome(outcome),
|
||||||
|
_ = cancel.cancelled() => Step::Cancelled,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
match step {
|
match step {
|
||||||
Step::Progress(event) => {
|
Step::Progress(event) => {
|
||||||
let frame = progress_frame(&call.token, &event);
|
let Some(peer) = &mut call.peer else { continue };
|
||||||
Some((Ok(Event::default().data(frame.to_string())), call))
|
// One send in flight; keep driving the original domain future/deadline, never a task.
|
||||||
}
|
let delivery = {
|
||||||
Step::Outcome(outcome) => {
|
let notify = peer.notify(event.progress, event.message);
|
||||||
call.finished = true;
|
tokio::pin!(notify);
|
||||||
let payload = match sdk_tools_payload(&call.message, &call.protocol_version, outcome) {
|
loop {
|
||||||
ToolCommandPayload::Ok(payload) => payload,
|
tokio::select! {
|
||||||
ToolCommandPayload::Internal(_) => jsonrpc_internal_error(&call.message),
|
biased;
|
||||||
};
|
result = &mut notify => break Some(result),
|
||||||
// The same projection point the single response uses, so a streamed answer delivers the
|
outcome = &mut call.call, if call.outcome.is_none() => {
|
||||||
// same closed `notifications/message` (Story 3.18) before its terminal frame.
|
let expired = is_deadline(&outcome);
|
||||||
crate::transport::note_logging_outcome(&payload);
|
call.outcome = Some(outcome);
|
||||||
for notification in crate::protocol::take_notifications() {
|
if expired { break None; }
|
||||||
|
}
|
||||||
|
_ = call.cancel.cancelled() => return None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
match delivery {
|
||||||
|
Some(Ok(frame)) => {
|
||||||
|
return Some((Ok(Event::default().data(frame.to_string())), call));
|
||||||
|
}
|
||||||
|
// Progress is optional: no retry, handwritten fallback or replay of the Tool.
|
||||||
|
Some(Err(_)) | None => {
|
||||||
|
if let Some(peer) = call.peer.take() {
|
||||||
|
peer.finish().await;
|
||||||
|
}
|
||||||
|
call.events.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Step::Outcome(outcome) => {
|
||||||
|
call.finished = true;
|
||||||
|
if let Some(peer) = call.peer.take() {
|
||||||
|
peer.finish().await;
|
||||||
|
}
|
||||||
|
let payload =
|
||||||
|
match sdk_tools_payload(&call.message, &call.protocol_version, outcome) {
|
||||||
|
ToolCommandPayload::Ok(payload) => payload,
|
||||||
|
ToolCommandPayload::Internal(_) => jsonrpc_internal_error(&call.message),
|
||||||
|
};
|
||||||
|
// The same projection point the single response uses, so a streamed answer delivers the
|
||||||
|
// same closed `notifications/message` (Story 3.18) before its terminal frame.
|
||||||
|
crate::transport::note_logging_outcome(&payload);
|
||||||
|
for notification in crate::protocol::take_notifications() {
|
||||||
|
call.pending
|
||||||
|
.push_back(Event::default().data(notification.to_string()));
|
||||||
|
}
|
||||||
call.pending
|
call.pending
|
||||||
.push_back(Event::default().data(notification.to_string()));
|
.push_back(Event::default().data(payload.to_string()));
|
||||||
|
return Some((Ok(call.pending.pop_front().expect("queued frame")), call));
|
||||||
|
}
|
||||||
|
Step::Cancelled => {
|
||||||
|
call.finished = true;
|
||||||
|
call.pending.clear();
|
||||||
|
return None;
|
||||||
}
|
}
|
||||||
call.pending
|
|
||||||
.push_back(Event::default().data(payload.to_string()));
|
|
||||||
Some((Ok(call.pending.pop_front().expect("queued frame")), call))
|
|
||||||
}
|
|
||||||
Step::Cancelled => {
|
|
||||||
call.finished = true;
|
|
||||||
call.pending.clear();
|
|
||||||
None
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn is_deadline(outcome: &super::rmcp_tools_runtime::Outcome) -> bool {
|
||||||
|
matches!(outcome, super::rmcp_tools_runtime::Outcome::Call(result)
|
||||||
|
if result.structured_content.as_ref().is_some_and(|value|
|
||||||
|
value["error"]["code"] == "upstream_timeout"))
|
||||||
|
}
|
||||||
|
|
||||||
fn jsonrpc_internal_error(message: &Value) -> Value {
|
fn jsonrpc_internal_error(message: &Value) -> Value {
|
||||||
crate::jsonrpc::jsonrpc_error(request_id(message), -32603, "internal server error")
|
crate::jsonrpc::jsonrpc_error(request_id(message), -32603, "internal server error")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "rmcp_progress_stream_tests.rs"]
|
||||||
|
mod stream_tests;
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
#[path = "lifecycle_tests.rs"]
|
#[path = "lifecycle_tests.rs"]
|
||||||
mod tests;
|
mod tests;
|
||||||
@@ -2,13 +2,14 @@
|
|||||||
//! progress queue, the pinned frame shape and the ownership of the in-flight cancellation table.
|
//! progress queue, the pinned frame shape and the ownership of the in-flight cancellation table.
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
fn token(value: Value) -> Option<ProgressToken> {
|
fn token(value: Value) -> Option<ProgressToken> {
|
||||||
progress_token(&json!({ "_meta": { "progressToken": value } }))
|
progress_token(&json!({ "_meta": { "progressToken": value } }))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[tokio::test]
|
||||||
fn rmcp_progress_cancel_frame_preserves_serialized_numbers_and_omissions() {
|
async fn rmcp_progress_cancel_frame_preserves_serialized_numbers_and_omissions() {
|
||||||
for wire_token in [
|
for wire_token in [
|
||||||
"\"token\"",
|
"\"token\"",
|
||||||
"-7",
|
"-7",
|
||||||
@@ -19,13 +20,9 @@ fn rmcp_progress_cancel_frame_preserves_serialized_numbers_and_omissions() {
|
|||||||
] {
|
] {
|
||||||
let value: Value = serde_json::from_str(wire_token).unwrap();
|
let value: Value = serde_json::from_str(wire_token).unwrap();
|
||||||
for progress in [2, 9_007_199_254_740_993, u64::MAX] {
|
for progress in [2, 9_007_199_254_740_993, u64::MAX] {
|
||||||
let frame = progress_frame(
|
let mut peer = super::super::rmcp_progress_peer::ProgressPeer::start(value.clone());
|
||||||
&token(value.clone()).unwrap(),
|
let frame = peer.notify(progress, "execution_dispatched").await.unwrap();
|
||||||
&ProgressEvent {
|
peer.finish().await;
|
||||||
progress,
|
|
||||||
message: "execution_dispatched",
|
|
||||||
},
|
|
||||||
);
|
|
||||||
assert_eq!(frame["params"]["progressToken"].to_string(), wire_token);
|
assert_eq!(frame["params"]["progressToken"].to_string(), wire_token);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
frame["params"]["progress"].to_string(),
|
frame["params"]["progress"].to_string(),
|
||||||
@@ -123,14 +120,15 @@ async fn without_a_token_no_progress_is_produced_at_all() {
|
|||||||
/// The pinned `notifications/progress` frame (schema `ProgressNotification`, both supported
|
/// The pinned `notifications/progress` frame (schema `ProgressNotification`, both supported
|
||||||
/// revisions): `progressToken` echoed verbatim, `progress` increasing, `message` optional and
|
/// revisions): `progressToken` echoed verbatim, `progress` increasing, `message` optional and
|
||||||
/// `total` absent because this server never invents one.
|
/// `total` absent because this server never invents one.
|
||||||
#[test]
|
#[tokio::test]
|
||||||
fn the_progress_frame_matches_the_pinned_notification_shape() {
|
async fn the_progress_frame_matches_the_pinned_notification_shape() {
|
||||||
let event = ProgressEvent {
|
let event = ProgressEvent {
|
||||||
progress: 2,
|
progress: 2,
|
||||||
message: Phase::Authorized.message(),
|
message: Phase::Authorized.message(),
|
||||||
};
|
};
|
||||||
|
let mut peer = super::super::rmcp_progress_peer::ProgressPeer::start(json!("tok-2"));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
progress_frame(&ProgressToken::Text("tok-2".to_owned()), &event),
|
peer.notify(event.progress, event.message).await.unwrap(),
|
||||||
json!({
|
json!({
|
||||||
"jsonrpc": "2.0",
|
"jsonrpc": "2.0",
|
||||||
"method": "notifications/progress",
|
"method": "notifications/progress",
|
||||||
@@ -141,10 +139,13 @@ fn the_progress_frame_matches_the_pinned_notification_shape() {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
peer.finish().await;
|
||||||
|
let mut peer = super::super::rmcp_progress_peer::ProgressPeer::start(json!(7));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
progress_frame(&ProgressToken::Number(7.into()), &event)["params"]["progressToken"],
|
peer.notify(event.progress, event.message).await.unwrap()["params"]["progressToken"],
|
||||||
json!(7)
|
json!(7)
|
||||||
);
|
);
|
||||||
|
peer.finish().await;
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
|
|||||||
@@ -0,0 +1,250 @@
|
|||||||
|
//! Request-owned outbound SDK peer for progress notifications.
|
||||||
|
use std::{
|
||||||
|
io,
|
||||||
|
sync::{Arc, Mutex},
|
||||||
|
};
|
||||||
|
|
||||||
|
use futures_util::{sink, stream};
|
||||||
|
use rmcp::{
|
||||||
|
RoleServer, ServerHandler,
|
||||||
|
model::{
|
||||||
|
ClientJsonRpcMessage, ProgressNotificationParam, ServerJsonRpcMessage, ServerNotification,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
use serde_json::Value;
|
||||||
|
use tokio::sync::{mpsc, oneshot, watch};
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "rmcp_progress_peer_controls.rs"]
|
||||||
|
pub(crate) mod controls;
|
||||||
|
|
||||||
|
const PROGRESS_TOKEN: &str = "progressToken";
|
||||||
|
// The SDK traces outbound params; client tokens must stay outside its pump.
|
||||||
|
const SDK_PROGRESS_TOKEN: &str = "crank-internal-progress";
|
||||||
|
|
||||||
|
struct Bootstrap;
|
||||||
|
impl ServerHandler for Bootstrap {}
|
||||||
|
|
||||||
|
struct SinkState {
|
||||||
|
sender: mpsc::Sender<Value>,
|
||||||
|
#[cfg(test)]
|
||||||
|
control: Option<controls::Controls>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) struct ProgressPeer {
|
||||||
|
token: Value,
|
||||||
|
receiver: mpsc::Receiver<Value>,
|
||||||
|
shutdown: Option<oneshot::Sender<()>>,
|
||||||
|
owner: Option<tokio::task::JoinHandle<()>>,
|
||||||
|
peer: watch::Receiver<Option<rmcp::service::Peer<RoleServer>>>,
|
||||||
|
#[cfg(test)]
|
||||||
|
controls: Option<controls::Controls>,
|
||||||
|
progress_sidecar: Arc<Mutex<Option<u64>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ProgressPeer {
|
||||||
|
pub(super) fn start(token: Value) -> Self {
|
||||||
|
#[cfg(test)]
|
||||||
|
let controls = controls::Controls::current();
|
||||||
|
let (sender, receiver) = mpsc::channel(1);
|
||||||
|
let owner_sender = sender.clone();
|
||||||
|
let (shutdown, shutdown_rx) = oneshot::channel();
|
||||||
|
let (peer_tx, peer) = watch::channel(None);
|
||||||
|
let progress_sidecar = Arc::new(Mutex::new(None::<u64>));
|
||||||
|
let sink_sidecar = progress_sidecar.clone();
|
||||||
|
let raw_token = token.clone();
|
||||||
|
let output = sink::unfold(
|
||||||
|
SinkState {
|
||||||
|
sender: sender.clone(),
|
||||||
|
#[cfg(test)]
|
||||||
|
control: controls.clone(),
|
||||||
|
},
|
||||||
|
move |state, message| {
|
||||||
|
let progress_sidecar = sink_sidecar.clone();
|
||||||
|
let raw_token = raw_token.clone();
|
||||||
|
async move {
|
||||||
|
#[cfg(test)]
|
||||||
|
if let Some(control) = &state.control {
|
||||||
|
control.entered();
|
||||||
|
if control.should_fail_send() {
|
||||||
|
return Err(io::Error::other("controlled progress send failure"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let ServerJsonRpcMessage::Notification(notification) = &message else {
|
||||||
|
return Err(io::Error::new(
|
||||||
|
io::ErrorKind::InvalidData,
|
||||||
|
"unexpected SDK progress output",
|
||||||
|
));
|
||||||
|
};
|
||||||
|
let ServerNotification::ProgressNotification(_) = ¬ification.notification
|
||||||
|
else {
|
||||||
|
return Err(io::Error::new(
|
||||||
|
io::ErrorKind::InvalidData,
|
||||||
|
"unexpected SDK progress notification",
|
||||||
|
));
|
||||||
|
};
|
||||||
|
let mut actual = serde_json::to_value(&message).map_err(io::Error::other)?;
|
||||||
|
if actual["params"][PROGRESS_TOKEN] != SDK_PROGRESS_TOKEN {
|
||||||
|
return Err(io::Error::new(
|
||||||
|
io::ErrorKind::InvalidData,
|
||||||
|
"unexpected SDK progress token",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let progress = progress_sidecar
|
||||||
|
.lock()
|
||||||
|
.expect("progress sidecar lock")
|
||||||
|
.take()
|
||||||
|
.ok_or_else(|| {
|
||||||
|
io::Error::new(io::ErrorKind::InvalidData, "missing progress sidecar")
|
||||||
|
})?;
|
||||||
|
actual["params"]["progress"] = Value::from(progress);
|
||||||
|
actual["params"][PROGRESS_TOKEN] = raw_token;
|
||||||
|
#[cfg(test)]
|
||||||
|
if state
|
||||||
|
.control
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(controls::Controls::should_mutate_message)
|
||||||
|
{
|
||||||
|
actual["params"]["message"] = Value::from("controlled output mutation");
|
||||||
|
}
|
||||||
|
state.sender.try_send(actual).map_err(|error| match error {
|
||||||
|
mpsc::error::TrySendError::Full(_) => {
|
||||||
|
io::Error::new(io::ErrorKind::WouldBlock, "progress output full")
|
||||||
|
}
|
||||||
|
mpsc::error::TrySendError::Closed(_) => {
|
||||||
|
io::Error::new(io::ErrorKind::BrokenPipe, "progress output closed")
|
||||||
|
}
|
||||||
|
})?;
|
||||||
|
#[cfg(test)]
|
||||||
|
if let Some(control) = &state.control {
|
||||||
|
control.queued();
|
||||||
|
control.wait_gate().await;
|
||||||
|
}
|
||||||
|
Ok::<_, io::Error>(state)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
#[cfg(test)]
|
||||||
|
let owner_controls = controls.clone();
|
||||||
|
let owner = tokio::spawn(async move {
|
||||||
|
let running = rmcp::service::serve_directly(
|
||||||
|
Bootstrap,
|
||||||
|
(Box::pin(output), stream::pending::<ClientJsonRpcMessage>()),
|
||||||
|
None,
|
||||||
|
);
|
||||||
|
let peer = running.peer().clone();
|
||||||
|
let _ = peer_tx.send(Some(peer));
|
||||||
|
let stop = running.cancellation_token();
|
||||||
|
let pump = running.waiting();
|
||||||
|
tokio::pin!(pump);
|
||||||
|
let mut pump_done = false;
|
||||||
|
tokio::select! {
|
||||||
|
_ = owner_sender.closed() => {},
|
||||||
|
_ = shutdown_rx => {},
|
||||||
|
_ = &mut pump => { pump_done = true; },
|
||||||
|
}
|
||||||
|
#[cfg(test)]
|
||||||
|
if let Some(control) = &owner_controls {
|
||||||
|
control.release_sink();
|
||||||
|
}
|
||||||
|
stop.cancel();
|
||||||
|
if !pump_done {
|
||||||
|
let _ = pump.await;
|
||||||
|
}
|
||||||
|
#[cfg(test)]
|
||||||
|
if let Some(control) = owner_controls {
|
||||||
|
control.completed();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Self {
|
||||||
|
token,
|
||||||
|
receiver,
|
||||||
|
shutdown: Some(shutdown),
|
||||||
|
owner: Some(owner),
|
||||||
|
peer,
|
||||||
|
#[cfg(test)]
|
||||||
|
controls,
|
||||||
|
progress_sidecar,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn notify(
|
||||||
|
&mut self,
|
||||||
|
progress: u64,
|
||||||
|
message: &'static str,
|
||||||
|
) -> Result<Value, io::Error> {
|
||||||
|
if !matches!(self.token, Value::String(_) | Value::Number(_)) {
|
||||||
|
return Err(io::Error::new(
|
||||||
|
io::ErrorKind::InvalidInput,
|
||||||
|
"invalid progress token",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let sdk_token = rmcp::model::ProgressToken(rmcp::model::NumberOrString::String(
|
||||||
|
SDK_PROGRESS_TOKEN.into(),
|
||||||
|
));
|
||||||
|
let params =
|
||||||
|
ProgressNotificationParam::new(sdk_token, progress as f64).with_message(message);
|
||||||
|
*self.progress_sidecar.lock().expect("progress sidecar lock") = Some(progress);
|
||||||
|
let mut peer = self.peer.clone();
|
||||||
|
while peer.borrow().is_none() {
|
||||||
|
peer.changed().await.map_err(io::Error::other)?;
|
||||||
|
}
|
||||||
|
let peer = peer.borrow().as_ref().expect("peer initialized").clone();
|
||||||
|
#[cfg(test)]
|
||||||
|
if let Some(control) = &self.controls {
|
||||||
|
control.sent();
|
||||||
|
}
|
||||||
|
let send = peer.notify_progress(params);
|
||||||
|
tokio::pin!(send);
|
||||||
|
let mut output = None;
|
||||||
|
let send_result = loop {
|
||||||
|
tokio::select! {
|
||||||
|
result = &mut send => break result,
|
||||||
|
received = self.receiver.recv(), if output.is_none() => {
|
||||||
|
output = Some(received.ok_or_else(|| io::Error::new(io::ErrorKind::BrokenPipe, "progress output closed"))?);
|
||||||
|
#[cfg(test)]
|
||||||
|
if let Some(control) = &self.controls { control.received(); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
send_result.map_err(io::Error::other)?;
|
||||||
|
let actual = match output {
|
||||||
|
Some(output) => output,
|
||||||
|
None => self.receiver.recv().await.ok_or_else(|| {
|
||||||
|
io::Error::new(io::ErrorKind::BrokenPipe, "progress output closed")
|
||||||
|
})?,
|
||||||
|
};
|
||||||
|
#[cfg(test)]
|
||||||
|
if let Some(control) = &self.controls {
|
||||||
|
control.consumed();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
super::dispatch_observer::sdk_progress_notification_serialized();
|
||||||
|
Ok(actual)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) async fn finish(mut self) {
|
||||||
|
self.close();
|
||||||
|
if let Some(owner) = self.owner.take() {
|
||||||
|
let _ = owner.await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn close(&mut self) {
|
||||||
|
self.receiver.close();
|
||||||
|
if let Some(shutdown) = self.shutdown.take() {
|
||||||
|
let _ = shutdown.send(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for ProgressPeer {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "../rmcp_progress_peer_tests.rs"]
|
||||||
|
mod tests;
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
//! Request-local test controls for the actual SDK progress peer.
|
||||||
|
#![cfg(test)]
|
||||||
|
|
||||||
|
use std::sync::{
|
||||||
|
Arc,
|
||||||
|
atomic::{AtomicBool, AtomicUsize, Ordering},
|
||||||
|
};
|
||||||
|
use tokio::sync::Semaphore;
|
||||||
|
|
||||||
|
tokio::task_local! {
|
||||||
|
static CURRENT: Controls;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Default)]
|
||||||
|
pub(crate) struct Controls(Arc<State>);
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct State {
|
||||||
|
actual_send: AtomicUsize,
|
||||||
|
sink_entered: AtomicUsize,
|
||||||
|
output_consumed: AtomicUsize,
|
||||||
|
output_received: AtomicUsize,
|
||||||
|
output_queued: AtomicUsize,
|
||||||
|
owner_completed: AtomicUsize,
|
||||||
|
fail_send: AtomicBool,
|
||||||
|
mutate_message: AtomicBool,
|
||||||
|
gate: std::sync::OnceLock<Arc<Semaphore>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Controls {
|
||||||
|
/// Installs controls only for this request future; `ProgressPeer::start` captures them.
|
||||||
|
pub(crate) async fn scope<F: std::future::Future>(controls: Controls, future: F) -> F::Output {
|
||||||
|
CURRENT.scope(controls, future).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn actual_send(&self) -> usize {
|
||||||
|
self.0.actual_send.load(Ordering::SeqCst)
|
||||||
|
}
|
||||||
|
pub(crate) fn sink_entered(&self) -> usize {
|
||||||
|
self.0.sink_entered.load(Ordering::SeqCst)
|
||||||
|
}
|
||||||
|
pub(crate) fn output_consumed(&self) -> usize {
|
||||||
|
self.0.output_consumed.load(Ordering::SeqCst)
|
||||||
|
}
|
||||||
|
pub(crate) fn output_queued(&self) -> usize {
|
||||||
|
self.0.output_queued.load(Ordering::SeqCst)
|
||||||
|
}
|
||||||
|
pub(crate) fn output_received(&self) -> usize {
|
||||||
|
self.0.output_received.load(Ordering::SeqCst)
|
||||||
|
}
|
||||||
|
pub(crate) fn owner_completed(&self) -> usize {
|
||||||
|
self.0.owner_completed.load(Ordering::SeqCst)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn fail_next_send(&self) {
|
||||||
|
self.0.fail_send.store(true, Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
pub(crate) fn mutate_output_message(&self) {
|
||||||
|
self.0.mutate_message.store(true, Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
pub(crate) fn hold_sink(&self) {
|
||||||
|
let _ = self.gate();
|
||||||
|
}
|
||||||
|
pub(crate) fn release_sink(&self) {
|
||||||
|
self.gate().close();
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn current() -> Option<Self> {
|
||||||
|
CURRENT.try_with(Clone::clone).ok()
|
||||||
|
}
|
||||||
|
pub(super) fn sent(&self) {
|
||||||
|
self.0.actual_send.fetch_add(1, Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
pub(super) fn entered(&self) {
|
||||||
|
self.0.sink_entered.fetch_add(1, Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
pub(super) fn consumed(&self) {
|
||||||
|
self.0.output_consumed.fetch_add(1, Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
pub(super) fn queued(&self) {
|
||||||
|
self.0.output_queued.fetch_add(1, Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
pub(super) fn received(&self) {
|
||||||
|
self.0.output_received.fetch_add(1, Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
pub(super) fn completed(&self) {
|
||||||
|
self.0.owner_completed.fetch_add(1, Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
pub(super) fn should_fail_send(&self) -> bool {
|
||||||
|
self.0.fail_send.swap(false, Ordering::SeqCst)
|
||||||
|
}
|
||||||
|
pub(super) fn should_mutate_message(&self) -> bool {
|
||||||
|
self.0.mutate_message.swap(false, Ordering::SeqCst)
|
||||||
|
}
|
||||||
|
pub(super) async fn wait_gate(&self) {
|
||||||
|
if let Some(gate) = self.0.gate.get() {
|
||||||
|
let _ = gate.acquire().await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn gate(&self) -> &Arc<Semaphore> {
|
||||||
|
self.0.gate.get_or_init(|| Arc::new(Semaphore::new(0)))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
//! Request-stream ownership controls without an external service or a second domain task.
|
||||||
|
use super::super::rmcp_progress_peer::{ProgressPeer, controls::Controls};
|
||||||
|
use super::*;
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
struct DomainLease(Arc<AtomicBool>);
|
||||||
|
impl Drop for DomainLease {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.0.store(true, Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn stream_call(
|
||||||
|
controls: &Controls,
|
||||||
|
deadline: bool,
|
||||||
|
) -> (
|
||||||
|
CallStream,
|
||||||
|
Arc<AtomicBool>,
|
||||||
|
Arc<InFlightCalls>,
|
||||||
|
InFlightScope,
|
||||||
|
) {
|
||||||
|
controls.hold_sink();
|
||||||
|
let dropped = Arc::new(AtomicBool::new(false));
|
||||||
|
let lease = DomainLease(dropped.clone());
|
||||||
|
let registry = Arc::new(InFlightCalls::new(1));
|
||||||
|
let scope = InFlightScope {
|
||||||
|
session_id: "owned".into(),
|
||||||
|
owner: "key".into(),
|
||||||
|
};
|
||||||
|
let entry = registry.register(&scope, &serde_json::json!(1)).unwrap();
|
||||||
|
let (lifecycle, events) = ToolCallLifecycle::new(Some(ProgressToken::Text("owned".into())));
|
||||||
|
let domain = async move {
|
||||||
|
let _lease = lease;
|
||||||
|
lifecycle.advance(Phase::Resolved);
|
||||||
|
if deadline {
|
||||||
|
tokio::time::sleep(Duration::from_millis(30)).await;
|
||||||
|
let mut result = rmcp::model::CallToolResult::error(vec![]);
|
||||||
|
result.structured_content =
|
||||||
|
Some(serde_json::json!({"error":{"code":"upstream_timeout"}}));
|
||||||
|
super::super::rmcp_tools_runtime::Outcome::Call(result)
|
||||||
|
} else {
|
||||||
|
std::future::pending().await
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let call = CallStream {
|
||||||
|
call: Box::pin(domain),
|
||||||
|
events: events.unwrap(),
|
||||||
|
cancel: entry.cancel_signal(),
|
||||||
|
peer: Some(ProgressPeer::start(serde_json::json!("owned"))),
|
||||||
|
outcome: None,
|
||||||
|
message: serde_json::json!({"jsonrpc":"2.0","id":1}),
|
||||||
|
protocol_version: crate::jsonrpc::LEGACY_PROTOCOL_VERSION.into(),
|
||||||
|
pending: VecDeque::new(),
|
||||||
|
finished: false,
|
||||||
|
logging: crate::protocol::carry_scope(),
|
||||||
|
_in_flight: Some(entry),
|
||||||
|
};
|
||||||
|
(call, dropped, registry, scope)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn joined(controls: &Controls) {
|
||||||
|
tokio::time::timeout(Duration::from_secs(2), async {
|
||||||
|
while controls.owner_completed() != 1 {
|
||||||
|
tokio::task::yield_now().await;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("request owner must join SDK pump");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn rmcp_progress_peer_unpolled_stream_drop_releases_owner_domain_and_registration() {
|
||||||
|
let controls = Controls::default();
|
||||||
|
Controls::scope(controls.clone(), async {
|
||||||
|
let (call, dropped, registry, scope) = stream_call(&controls, false);
|
||||||
|
drop(call);
|
||||||
|
joined(&controls).await;
|
||||||
|
assert!(dropped.load(Ordering::SeqCst));
|
||||||
|
assert_eq!(controls.actual_send(), 0);
|
||||||
|
assert!(registry.register(&scope, &serde_json::json!(1)).is_some());
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn rmcp_progress_peer_pending_send_cancel_stops_domain_and_joins_pump() {
|
||||||
|
let controls = Controls::default();
|
||||||
|
Controls::scope(controls.clone(), async {
|
||||||
|
let (call, dropped, registry, scope) = stream_call(&controls, false);
|
||||||
|
let next = next_event(call);
|
||||||
|
tokio::pin!(next);
|
||||||
|
tokio::select! {
|
||||||
|
_ = &mut next => panic!("held send cannot produce a frame"),
|
||||||
|
_ = async { while controls.sink_entered() == 0 { tokio::task::yield_now().await; } } => {}
|
||||||
|
}
|
||||||
|
assert!(registry.cancel(&scope, &serde_json::json!(1)));
|
||||||
|
assert!(tokio::time::timeout(Duration::from_secs(2), &mut next).await.unwrap().is_none());
|
||||||
|
joined(&controls).await;
|
||||||
|
assert!(dropped.load(Ordering::SeqCst));
|
||||||
|
assert_eq!(controls.output_consumed(), 0);
|
||||||
|
assert!(registry.register(&scope, &serde_json::json!(1)).is_some());
|
||||||
|
}).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn rmcp_progress_peer_pending_send_body_drop_stops_domain_and_joins_pump() {
|
||||||
|
let controls = Controls::default();
|
||||||
|
Controls::scope(controls.clone(), async {
|
||||||
|
let (call, dropped, registry, scope) = stream_call(&controls, false);
|
||||||
|
let mut next = Box::pin(next_event(call));
|
||||||
|
tokio::time::timeout(Duration::from_secs(2), async {
|
||||||
|
tokio::select! {
|
||||||
|
_ = &mut next => panic!("held send cannot produce a frame"),
|
||||||
|
_ = async { while controls.sink_entered() == 0 { tokio::task::yield_now().await; } } => {}
|
||||||
|
}
|
||||||
|
}).await.unwrap();
|
||||||
|
drop(next);
|
||||||
|
joined(&controls).await;
|
||||||
|
assert!(dropped.load(Ordering::SeqCst));
|
||||||
|
assert_eq!(controls.output_consumed(), 0);
|
||||||
|
assert!(registry.register(&scope, &serde_json::json!(1)).is_some());
|
||||||
|
}).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn rmcp_progress_peer_failure_after_first_frame_preserves_terminal_without_fallback() {
|
||||||
|
let controls = Controls::default();
|
||||||
|
Controls::scope(controls.clone(), async {
|
||||||
|
let (call, _, _, _) = stream_call(&controls, false);
|
||||||
|
controls.release_sink();
|
||||||
|
let (_, mut call) = next_event(call).await.expect("first actual SDK progress");
|
||||||
|
assert_eq!(controls.output_consumed(), 1);
|
||||||
|
controls.fail_next_send();
|
||||||
|
let (sender, events) = mpsc::channel(PROGRESS_CAPACITY);
|
||||||
|
sender
|
||||||
|
.try_send(ProgressEvent {
|
||||||
|
progress: 2,
|
||||||
|
message: "execution_dispatched",
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
call.events = events;
|
||||||
|
call.call = Box::pin(async {
|
||||||
|
super::super::rmcp_tools_runtime::Outcome::Call(rmcp::model::CallToolResult::success(
|
||||||
|
vec![],
|
||||||
|
))
|
||||||
|
});
|
||||||
|
let (_, call) = next_event(call)
|
||||||
|
.await
|
||||||
|
.expect("original terminal after send error");
|
||||||
|
assert!(
|
||||||
|
call.finished,
|
||||||
|
"no fallback progress in place of failed SDK send"
|
||||||
|
);
|
||||||
|
assert!(call.peer.is_none());
|
||||||
|
assert_eq!(controls.actual_send(), 2);
|
||||||
|
assert_eq!(controls.output_consumed(), 1);
|
||||||
|
assert_eq!(controls.owner_completed(), 1);
|
||||||
|
assert!(next_event(call).await.is_none(), "terminal stays last");
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn rmcp_progress_peer_pending_send_keeps_original_domain_deadline() {
|
||||||
|
let controls = Controls::default();
|
||||||
|
Controls::scope(controls.clone(), async {
|
||||||
|
let (call, dropped, registry, scope) = stream_call(&controls, true);
|
||||||
|
let (_, call) = tokio::time::timeout(Duration::from_secs(2), next_event(call))
|
||||||
|
.await
|
||||||
|
.expect("domain deadline must not wait for held send")
|
||||||
|
.unwrap();
|
||||||
|
assert!(call.finished);
|
||||||
|
assert!(call.peer.is_none());
|
||||||
|
assert_eq!(controls.sink_entered(), 1);
|
||||||
|
assert_eq!(controls.output_consumed(), 0);
|
||||||
|
joined(&controls).await;
|
||||||
|
assert!(dropped.load(Ordering::SeqCst));
|
||||||
|
drop(call);
|
||||||
|
assert!(registry.register(&scope, &serde_json::json!(1)).is_some());
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
}
|
||||||
@@ -196,8 +196,7 @@ impl ServerHandler for RmcpTools {
|
|||||||
event = async { match events.as_mut() { Some(events) => events.recv().await, None => std::future::pending().await } } => {
|
event = async { match events.as_mut() { Some(events) => events.recv().await, None => std::future::pending().await } } => {
|
||||||
if let Some(event) = event {
|
if let Some(event) = event {
|
||||||
if let Some(token) = &token {
|
if let Some(token) = &token {
|
||||||
let params = serde_json::from_value(super::lifecycle::progress_frame(token, &event)["params"].clone()).map_err(|_| McpError::internal_error("invalid progress event", None))?;
|
let _ = context.peer.notify_progress(event.sdk_params(token)).await;
|
||||||
let _ = context.peer.notify_progress(params).await;
|
|
||||||
}
|
}
|
||||||
} else { events = None; }
|
} else { events = None; }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ use tokio::sync::Semaphore;
|
|||||||
pub(in crate::app::dispatch_observer) struct Endpoint {
|
pub(in crate::app::dispatch_observer) struct Endpoint {
|
||||||
pub registry: crank_registry::PostgresRegistry,
|
pub registry: crank_registry::PostgresRegistry,
|
||||||
pub counters: Arc<CounterSet>,
|
pub counters: Arc<CounterSet>,
|
||||||
|
pub peer_controls: crate::app::rmcp_progress_peer::controls::Controls,
|
||||||
pub sessions: Arc<CountedSessionStore>,
|
pub sessions: Arc<CountedSessionStore>,
|
||||||
pub key: String,
|
pub key: String,
|
||||||
pub other_key: String,
|
pub other_key: String,
|
||||||
@@ -110,11 +111,18 @@ impl Endpoint {
|
|||||||
Arc::new(crate::auth::CommunityMachineCredentialVerifier),
|
Arc::new(crate::auth::CommunityMachineCredentialVerifier),
|
||||||
);
|
);
|
||||||
let scope = counters.clone();
|
let scope = counters.clone();
|
||||||
|
let peer_controls = crate::app::rmcp_progress_peer::controls::Controls::default();
|
||||||
|
let peer_scope = peer_controls.clone();
|
||||||
let app = app.layer(axum::middleware::from_fn(
|
let app = app.layer(axum::middleware::from_fn(
|
||||||
move |request: axum::extract::Request, next: axum::middleware::Next| {
|
move |request: axum::extract::Request, next: axum::middleware::Next| {
|
||||||
let c = scope.clone();
|
let c = scope.clone();
|
||||||
|
let control = peer_scope.clone();
|
||||||
async move {
|
async move {
|
||||||
let response = observe(c.clone(), next.run(request)).await;
|
let response = crate::app::rmcp_progress_peer::controls::Controls::scope(
|
||||||
|
control,
|
||||||
|
observe(c.clone(), next.run(request)),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
observe_body(response, c)
|
observe_body(response, c)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -130,6 +138,7 @@ impl Endpoint {
|
|||||||
Self {
|
Self {
|
||||||
registry,
|
registry,
|
||||||
counters,
|
counters,
|
||||||
|
peer_controls,
|
||||||
sessions,
|
sessions,
|
||||||
key,
|
key,
|
||||||
other_key,
|
other_key,
|
||||||
|
|||||||
@@ -8,6 +8,9 @@ use std::{sync::Arc, time::Duration};
|
|||||||
pub(super) mod fixtures;
|
pub(super) mod fixtures;
|
||||||
use fixtures::Endpoint;
|
use fixtures::Endpoint;
|
||||||
|
|
||||||
|
#[path = "rmcp_progress_peer_runtime_tests.rs"]
|
||||||
|
mod peer_runtime;
|
||||||
|
|
||||||
fn observe_body(response: Response, counters: Arc<CounterSet>) -> Response {
|
fn observe_body(response: Response, counters: Arc<CounterSet>) -> Response {
|
||||||
let (parts, body) = response.into_parts();
|
let (parts, body) = response.into_parts();
|
||||||
let body = stream::unfold(
|
let body = stream::unfold(
|
||||||
|
|||||||
@@ -0,0 +1,77 @@
|
|||||||
|
//! Actual SDK send/output controls through the ordinary HTTP/SSE consumer.
|
||||||
|
use super::*;
|
||||||
|
use std::sync::atomic::Ordering;
|
||||||
|
|
||||||
|
async fn peer_output_control(revision: &str) {
|
||||||
|
let h = Endpoint::started().await;
|
||||||
|
let session = h.session(revision).await;
|
||||||
|
let controls = &h.peer_controls;
|
||||||
|
controls.mutate_output_message();
|
||||||
|
h.gate.add_permits(1);
|
||||||
|
let reply = frames(
|
||||||
|
h.call(
|
||||||
|
revision,
|
||||||
|
session.as_deref(),
|
||||||
|
json!(61),
|
||||||
|
Some(json!(1.0)),
|
||||||
|
"text/event-stream",
|
||||||
|
)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(reply.len(), 4);
|
||||||
|
assert_eq!(
|
||||||
|
reply[0]["params"]["message"], "controlled output mutation",
|
||||||
|
"SSE must consume actual SDK output, not a parallel handwritten frame"
|
||||||
|
);
|
||||||
|
assert_eq!(reply[0]["params"]["progressToken"].to_string(), "1.0");
|
||||||
|
terminal(&reply, revision, json!(61));
|
||||||
|
assert_eq!(controls.actual_send(), 3);
|
||||||
|
assert_eq!(controls.sink_entered(), 3);
|
||||||
|
assert_eq!(controls.output_consumed(), 3);
|
||||||
|
assert_eq!(controls.owner_completed(), 1);
|
||||||
|
assert_eq!(h.started.load(Ordering::SeqCst), 1);
|
||||||
|
|
||||||
|
controls.fail_next_send();
|
||||||
|
h.gate.add_permits(1);
|
||||||
|
let reply = frames(
|
||||||
|
h.call(
|
||||||
|
revision,
|
||||||
|
session.as_deref(),
|
||||||
|
json!(62),
|
||||||
|
Some(json!("failed-send")),
|
||||||
|
"text/event-stream",
|
||||||
|
)
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
assert_eq!(
|
||||||
|
reply.len(),
|
||||||
|
1,
|
||||||
|
"failed SDK send disables progress without fallback"
|
||||||
|
);
|
||||||
|
terminal(&reply, revision, json!(62));
|
||||||
|
assert_eq!(controls.actual_send(), 4, "no SDK retry/restart");
|
||||||
|
assert_eq!(controls.sink_entered(), 4);
|
||||||
|
assert_eq!(
|
||||||
|
controls.output_consumed(),
|
||||||
|
3,
|
||||||
|
"failed output cannot count as delivered"
|
||||||
|
);
|
||||||
|
assert_eq!(controls.owner_completed(), 2);
|
||||||
|
assert_eq!(h.started.load(Ordering::SeqCst), 2, "same Tool, no replay");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn rmcp_progress_peer_runtime_legacy() {
|
||||||
|
peer_output_control(LEGACY_REVISION).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn rmcp_progress_peer_runtime_modern() {
|
||||||
|
peer_output_control(MODERN_REVISION).await;
|
||||||
|
}
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
use super::ProgressPeer;
|
||||||
|
use super::controls::Controls;
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use std::{
|
||||||
|
io::Write,
|
||||||
|
sync::{Arc, Mutex},
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Clone, Default)]
|
||||||
|
struct LogCapture(Arc<Mutex<Vec<u8>>>);
|
||||||
|
|
||||||
|
impl Write for LogCapture {
|
||||||
|
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
|
||||||
|
self.0.lock().unwrap().extend_from_slice(bytes);
|
||||||
|
Ok(bytes.len())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn flush(&mut self) -> std::io::Result<()> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for LogCapture {
|
||||||
|
type Writer = Self;
|
||||||
|
fn make_writer(&'a self) -> Self {
|
||||||
|
self.clone()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sdk_trace_keeps_raw_string_and_numeric_tokens_private_without_disabling_logs() {
|
||||||
|
let capture = LogCapture::default();
|
||||||
|
let subscriber = tracing_subscriber::fmt()
|
||||||
|
.with_max_level(tracing::Level::TRACE)
|
||||||
|
.without_time()
|
||||||
|
.with_ansi(false)
|
||||||
|
.with_writer(capture.clone())
|
||||||
|
.finish();
|
||||||
|
let dispatch = tracing::Dispatch::new(subscriber);
|
||||||
|
let _guard = tracing::dispatcher::set_default(&dispatch);
|
||||||
|
// All spawned pump tasks run under this thread's TRACE capture, not just the caller.
|
||||||
|
tokio::runtime::Builder::new_current_thread()
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
.unwrap()
|
||||||
|
.block_on(async {
|
||||||
|
for raw in [
|
||||||
|
"\"private-progress-canary-716283941\"",
|
||||||
|
"-716283941",
|
||||||
|
"1.572839416",
|
||||||
|
"1.0",
|
||||||
|
"-0.0",
|
||||||
|
"18446744073709551615",
|
||||||
|
"7.182736451928374651e+27",
|
||||||
|
] {
|
||||||
|
let token: Value = serde_json::from_str(raw).unwrap();
|
||||||
|
let mut peer = ProgressPeer::start(token.clone());
|
||||||
|
let output = peer.notify(u64::MAX, "running").await.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
output["params"]["progressToken"].to_string(),
|
||||||
|
token.to_string()
|
||||||
|
);
|
||||||
|
assert_eq!(output["params"]["progress"], json!(u64::MAX));
|
||||||
|
peer.finish().await;
|
||||||
|
}
|
||||||
|
tracing::info!("application-log-still-enabled");
|
||||||
|
});
|
||||||
|
let logs = String::from_utf8(capture.0.lock().unwrap().clone()).unwrap();
|
||||||
|
assert!(logs.contains("application-log-still-enabled"));
|
||||||
|
let notifications: Vec<_> = logs
|
||||||
|
.lines()
|
||||||
|
.filter(|line| line.contains("ProxyMessage(Notification"))
|
||||||
|
.collect();
|
||||||
|
assert_eq!(notifications.len(), 7, "actual SDK TRACE must be captured");
|
||||||
|
assert!(
|
||||||
|
notifications
|
||||||
|
.iter()
|
||||||
|
.all(|line| line.contains("ProgressToken(String(\"crank-internal-progress\"))"))
|
||||||
|
);
|
||||||
|
for raw in [
|
||||||
|
"private-progress-canary-716283941",
|
||||||
|
"-716283941",
|
||||||
|
"1.572839416",
|
||||||
|
"18446744073709551615",
|
||||||
|
"7.182736451928374651",
|
||||||
|
] {
|
||||||
|
assert!(!logs.contains(raw), "raw token leaked into SDK TRACE");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn emits_real_sdk_progress_notification_with_exact_raw_numbers() {
|
||||||
|
let token: Value = serde_json::from_str("1.0").unwrap();
|
||||||
|
let mut peer = ProgressPeer::start(token);
|
||||||
|
let output = peer.notify(9_007_199_254_740_993, "running").await.unwrap();
|
||||||
|
assert_eq!(output["method"], "notifications/progress");
|
||||||
|
assert_eq!(output["params"]["progressToken"].to_string(), "1.0");
|
||||||
|
assert_eq!(
|
||||||
|
output["params"]["progress"],
|
||||||
|
json!(9_007_199_254_740_993u64)
|
||||||
|
);
|
||||||
|
assert_eq!(output["params"]["message"], "running");
|
||||||
|
peer.finish().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn reports_output_send_failure_instead_of_claiming_delivery() {
|
||||||
|
let mut peer = ProgressPeer::start(json!(4));
|
||||||
|
peer.receiver.close();
|
||||||
|
assert!(peer.notify(2, "running").await.is_err());
|
||||||
|
peer.finish().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn request_controls_observe_mutated_actual_sdk_output_and_owner_shutdown() {
|
||||||
|
let controls = Controls::default();
|
||||||
|
controls.mutate_output_message();
|
||||||
|
Controls::scope(controls.clone(), async {
|
||||||
|
let mut peer = ProgressPeer::start(json!(4));
|
||||||
|
let output = peer.notify(2, "running").await.unwrap();
|
||||||
|
assert_eq!(output["params"]["message"], "controlled output mutation");
|
||||||
|
peer.finish().await;
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
assert_eq!(controls.actual_send(), 1);
|
||||||
|
assert_eq!(controls.sink_entered(), 1);
|
||||||
|
assert_eq!(controls.output_consumed(), 1);
|
||||||
|
assert_eq!(controls.owner_completed(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn failed_sdk_send_does_not_claim_output() {
|
||||||
|
let controls = Controls::default();
|
||||||
|
controls.fail_next_send();
|
||||||
|
Controls::scope(controls.clone(), async {
|
||||||
|
let mut peer = ProgressPeer::start(json!(4));
|
||||||
|
assert!(peer.notify(2, "running").await.is_err());
|
||||||
|
peer.finish().await;
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
assert_eq!(controls.actual_send(), 1);
|
||||||
|
assert_eq!(controls.sink_entered(), 1);
|
||||||
|
assert_eq!(controls.output_consumed(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn sink_gate_holds_responder_after_output_and_cleans_up_on_release() {
|
||||||
|
let controls = Controls::default();
|
||||||
|
controls.hold_sink();
|
||||||
|
Controls::scope(controls.clone(), async {
|
||||||
|
let mut peer = ProgressPeer::start(json!(4));
|
||||||
|
{
|
||||||
|
let send = peer.notify(2, "running");
|
||||||
|
tokio::pin!(send);
|
||||||
|
tokio::time::timeout(std::time::Duration::from_secs(2), async {
|
||||||
|
while controls.output_received() == 0 {
|
||||||
|
tokio::select! {
|
||||||
|
result = &mut send => panic!("send completed before gate release: {result:?}"),
|
||||||
|
_ = tokio::task::yield_now() => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}).await.expect("SDK output received while responder is gated");
|
||||||
|
assert_eq!(controls.output_consumed(), 0);
|
||||||
|
controls.release_sink();
|
||||||
|
assert!(send.await.is_ok());
|
||||||
|
}
|
||||||
|
peer.finish().await;
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
assert_eq!(controls.owner_completed(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn dropping_pending_gated_send_releases_and_joins_owner() {
|
||||||
|
let controls = Controls::default();
|
||||||
|
controls.hold_sink();
|
||||||
|
Controls::scope(controls.clone(), async {
|
||||||
|
let mut peer = ProgressPeer::start(json!(4));
|
||||||
|
{
|
||||||
|
let send = peer.notify(2, "running");
|
||||||
|
tokio::pin!(send);
|
||||||
|
tokio::time::timeout(std::time::Duration::from_secs(2), async {
|
||||||
|
while controls.output_queued() == 0 {
|
||||||
|
tokio::select! {
|
||||||
|
result = &mut send => panic!("send completed before drop: {result:?}"),
|
||||||
|
_ = tokio::task::yield_now() => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("SDK output queued before pending send drop");
|
||||||
|
}
|
||||||
|
peer.finish().await;
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
assert_eq!(controls.owner_completed(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn raw_numeric_tokens_and_counts_survive_sdk_projection() {
|
||||||
|
for token in ["-7", "1.5", "-0", "18446744073709551615"] {
|
||||||
|
let token: Value = serde_json::from_str(token).unwrap();
|
||||||
|
let mut peer = ProgressPeer::start(token.clone());
|
||||||
|
let output = peer.notify(u64::MAX, "running").await.unwrap();
|
||||||
|
assert_eq!(output["params"]["progressToken"], token);
|
||||||
|
assert_eq!(output["params"]["progress"], json!(u64::MAX));
|
||||||
|
peer.finish().await;
|
||||||
|
}
|
||||||
|
let token: Value = serde_json::from_str("1.0").unwrap();
|
||||||
|
let mut peer = ProgressPeer::start(token.clone());
|
||||||
|
let output = peer.notify(9_007_199_254_740_993, "running").await.unwrap();
|
||||||
|
assert_eq!(output["params"]["progressToken"], token);
|
||||||
|
assert_eq!(
|
||||||
|
output["params"]["progress"],
|
||||||
|
json!(9_007_199_254_740_993u64)
|
||||||
|
);
|
||||||
|
peer.finish().await;
|
||||||
|
}
|
||||||
@@ -217,13 +217,13 @@ string_enum! {
|
|||||||
Concurrency => "concurrency",
|
Concurrency => "concurrency",
|
||||||
RateLimit => "rate_limit",
|
RateLimit => "rate_limit",
|
||||||
McpStream => "mcp_stream",
|
McpStream => "mcp_stream",
|
||||||
Admission => "admission",
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
string_enum! {
|
string_enum! {
|
||||||
pub enum RejectionReason {
|
pub enum RejectionReason {
|
||||||
Limit => "limit",
|
|
||||||
Capacity => "capacity",
|
Capacity => "capacity",
|
||||||
QueueFull => "queue_full",
|
QueueFull => "queue_full",
|
||||||
Deadline => "deadline",
|
Deadline => "deadline",
|
||||||
@@ -234,7 +234,7 @@ string_enum! {
|
|||||||
|
|
||||||
string_enum! {
|
string_enum! {
|
||||||
pub enum ScopeKind {
|
pub enum ScopeKind {
|
||||||
Process => "process",
|
|
||||||
Global => "global",
|
Global => "global",
|
||||||
Agent => "agent",
|
Agent => "agent",
|
||||||
Tool => "tool",
|
Tool => "tool",
|
||||||
|
|||||||
@@ -350,24 +350,18 @@ pub fn record_limit_rejection(stage: LimitStage) {
|
|||||||
if bound_family("crank_runtime_limit_rejections_total").is_none() {
|
if bound_family("crank_runtime_limit_rejections_total").is_none() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
metrics::counter!(
|
metrics::counter!("crank_runtime_limit_rejections_total", "stage" => stage.as_str())
|
||||||
"crank_runtime_limit_rejections_total",
|
.increment(1);
|
||||||
"stage" => stage.as_str(),
|
|
||||||
"reason" => RejectionReason::Limit.as_str(),
|
|
||||||
"scope_kind" => ScopeKind::Process.as_str()
|
|
||||||
)
|
|
||||||
.increment(1);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Typed admission refusal with finite, low-cardinality labels only: no workspace, Agent, Tool,
|
/// Typed admission refusal with finite, low-cardinality labels only: no workspace, Agent, Tool,
|
||||||
/// request id, fingerprint or arbitrary error text ever becomes a label.
|
/// request id, fingerprint or arbitrary error text ever becomes a label.
|
||||||
pub fn record_admission_rejection(reason: RejectionReason, scope_kind: ScopeKind) {
|
pub fn record_admission_rejection(reason: RejectionReason, scope_kind: ScopeKind) {
|
||||||
if bound_family("crank_runtime_limit_rejections_total").is_none() {
|
if bound_family("crank_runtime_admission_rejections_total").is_none() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
metrics::counter!(
|
metrics::counter!(
|
||||||
"crank_runtime_limit_rejections_total",
|
"crank_runtime_admission_rejections_total",
|
||||||
"stage" => LimitStage::Admission.as_str(),
|
|
||||||
"reason" => reason.as_str(),
|
"reason" => reason.as_str(),
|
||||||
"scope_kind" => scope_kind.as_str()
|
"scope_kind" => scope_kind.as_str()
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -407,16 +407,26 @@ pub(crate) const METRIC_SCHEMA: &[MetricDefinition] = &[
|
|||||||
"crank_runtime_limit_rejections_total",
|
"crank_runtime_limit_rejections_total",
|
||||||
MetricKind::Counter,
|
MetricKind::Counter,
|
||||||
MetricUnit::Count,
|
MetricUnit::Count,
|
||||||
&["stage", "reason", "scope_kind"],
|
&["stage"],
|
||||||
|
&[domain("stage", LIMIT_STAGES)],
|
||||||
|
&[],
|
||||||
|
BOTH,
|
||||||
|
3,
|
||||||
|
"Runtime executions rejected by a bounded limit.",
|
||||||
|
),
|
||||||
|
metric(
|
||||||
|
"crank_runtime_admission_rejections_total",
|
||||||
|
MetricKind::Counter,
|
||||||
|
MetricUnit::Count,
|
||||||
|
&["reason", "scope_kind"],
|
||||||
&[
|
&[
|
||||||
domain("stage", LIMIT_STAGES),
|
|
||||||
domain("reason", REJECTION_REASONS),
|
domain("reason", REJECTION_REASONS),
|
||||||
domain("scope_kind", SCOPE_KINDS),
|
domain("scope_kind", SCOPE_KINDS),
|
||||||
],
|
],
|
||||||
&[],
|
&[],
|
||||||
BOTH,
|
BOTH,
|
||||||
96,
|
15,
|
||||||
"Runtime executions rejected by a bounded limit.",
|
"Runtime executions rejected by scoped admission.",
|
||||||
),
|
),
|
||||||
metric(
|
metric(
|
||||||
"crank_runtime_admission_queue_wait_seconds",
|
"crank_runtime_admission_queue_wait_seconds",
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ use crank_metrics::{
|
|||||||
record_mcp_request, record_tool_invocation, record_upstream_request, set_catalog,
|
record_mcp_request, record_tool_invocation, record_upstream_request, set_catalog,
|
||||||
set_db_pool_connections, set_mcp_active_sessions, set_mcp_session_metrics_fresh,
|
set_db_pool_connections, set_mcp_active_sessions, set_mcp_session_metrics_fresh,
|
||||||
};
|
};
|
||||||
use metrics_util::debugging::DebuggingRecorder;
|
use metrics_util::debugging::{DebugValue, DebuggingRecorder};
|
||||||
|
|
||||||
/// Service binding is process-global (`OnceLock`), so every case that needs a
|
/// Service binding is process-global (`OnceLock`), so every case that needs a
|
||||||
/// different service runs in a fresh child re-executed from this same test
|
/// different service runs in a fresh child re-executed from this same test
|
||||||
@@ -282,6 +282,33 @@ fn every_recording_api_matches_the_declared_schema() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
let snapshot = snapshotter.snapshot().into_vec();
|
let snapshot = snapshotter.snapshot().into_vec();
|
||||||
|
for (name, labels) in [
|
||||||
|
(
|
||||||
|
"crank_runtime_limit_rejections_total",
|
||||||
|
BTreeSet::from([("stage", "concurrency")]),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"crank_runtime_admission_rejections_total",
|
||||||
|
BTreeSet::from([("reason", "capacity"), ("scope_kind", "global")]),
|
||||||
|
),
|
||||||
|
] {
|
||||||
|
let mut samples = snapshot
|
||||||
|
.iter()
|
||||||
|
.filter(|(key, _, _, _)| key.key().name() == name);
|
||||||
|
let (key, _, _, value) = samples.next().expect(name);
|
||||||
|
assert!(
|
||||||
|
samples.next().is_none(),
|
||||||
|
"unexpected extra series for {name}"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
key.key()
|
||||||
|
.labels()
|
||||||
|
.map(|label| (label.key(), label.value()))
|
||||||
|
.collect::<BTreeSet<_>>(),
|
||||||
|
labels
|
||||||
|
);
|
||||||
|
assert!(matches!(value, DebugValue::Counter(1)), "{name}: {value:?}");
|
||||||
|
}
|
||||||
let actual_names = snapshot
|
let actual_names = snapshot
|
||||||
.iter()
|
.iter()
|
||||||
.map(|(key, _, _, _)| key.key().name().to_owned())
|
.map(|(key, _, _, _)| key.key().name().to_owned())
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ use crank_metrics::{
|
|||||||
#[test]
|
#[test]
|
||||||
fn schema_v1_is_complete_deterministic_and_inside_the_frozen_budget() {
|
fn schema_v1_is_complete_deterministic_and_inside_the_frozen_budget() {
|
||||||
assert_eq!(METRIC_SCHEMA_VERSION, 2);
|
assert_eq!(METRIC_SCHEMA_VERSION, 2);
|
||||||
assert_eq!(metric_schema().len(), 23);
|
assert_eq!(metric_schema().len(), 26);
|
||||||
|
|
||||||
for service in [MetricService::AdminApi, MetricService::McpServer] {
|
for service in [MetricService::AdminApi, MetricService::McpServer] {
|
||||||
let budget = schema_budget(service).expect("canonical schema must be valid");
|
let budget = schema_budget(service).expect("canonical schema must be valid");
|
||||||
@@ -79,15 +79,15 @@ fn canonical_schema_validation_reports_its_category() {
|
|||||||
assert_eq!(
|
assert_eq!(
|
||||||
schema_budget(MetricService::AdminApi),
|
schema_budget(MetricService::AdminApi),
|
||||||
Ok(crank_metrics::SchemaBudget {
|
Ok(crank_metrics::SchemaBudget {
|
||||||
logical_series: 6_381,
|
logical_series: 6_303,
|
||||||
rendered_series: 19_611
|
rendered_series: 19_533
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
schema_budget(MetricService::McpServer),
|
schema_budget(MetricService::McpServer),
|
||||||
Ok(crank_metrics::SchemaBudget {
|
Ok(crank_metrics::SchemaBudget {
|
||||||
logical_series: 1_179,
|
logical_series: 1_101,
|
||||||
rendered_series: 3_654
|
rendered_series: 3_576
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -343,13 +343,25 @@ fn v1_and_v2_registries_are_metric_by_metric_compatible() {
|
|||||||
let v1 = metric_objects(V1);
|
let v1 = metric_objects(V1);
|
||||||
let v2 = metric_objects(V2);
|
let v2 = metric_objects(V2);
|
||||||
assert_eq!(v1.len(), 23);
|
assert_eq!(v1.len(), 23);
|
||||||
|
let admission_families = [
|
||||||
|
"crank_runtime_admission_rejections_total",
|
||||||
|
"crank_runtime_admission_queue_wait_seconds",
|
||||||
|
"crank_runtime_admission_oldest_waiting_seconds",
|
||||||
|
];
|
||||||
|
let (admission, v2_legacy): (Vec<_>, Vec<_>) = v2
|
||||||
|
.iter()
|
||||||
|
.partition(|(name, _)| admission_families.contains(&name.as_str()));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
v1.iter().map(|(name, _)| name.clone()).collect::<Vec<_>>(),
|
admission
|
||||||
v2.iter().map(|(name, _)| name.clone()).collect::<Vec<_>>(),
|
.iter()
|
||||||
"v2 обязан сохранить тот же набор и порядок family"
|
.map(|(name, _)| name.as_str())
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
|
admission_families
|
||||||
);
|
);
|
||||||
|
assert_eq!(v1.len(), v2_legacy.len());
|
||||||
|
|
||||||
for ((name, v1_object), (_, v2_object)) in v1.iter().zip(v2.iter()) {
|
for ((name, v1_object), (v2_name, v2_object)) in v1.iter().zip(v2_legacy) {
|
||||||
|
assert_eq!(name, v2_name, "v2 обязан сохранить порядок v1 family");
|
||||||
for field in ["kind", "unit", "help", "processes", "buckets_seconds"] {
|
for field in ["kind", "unit", "help", "processes", "buckets_seconds"] {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
json_field(v1_object, field),
|
json_field(v1_object, field),
|
||||||
|
|||||||
@@ -543,22 +543,22 @@ fn root_budgets_are_per_process_only() {
|
|||||||
"root обязан объявлять ровно один ключ budgets"
|
"root обязан объявлять ровно один ключ budgets"
|
||||||
);
|
);
|
||||||
assert!(rendered.ends_with(
|
assert!(rendered.ends_with(
|
||||||
",\"budgets\":[{\"process\":\"admin_api\",\"families\":17,\"logical_series\":6381,\
|
",\"budgets\":[{\"process\":\"admin_api\",\"families\":18,\"logical_series\":6303,\
|
||||||
\"rendered_series\":19611,\"exemplar_slots\":12348},{\"process\":\"mcp_server\",\
|
\"rendered_series\":19533,\"exemplar_slots\":12348},{\"process\":\"mcp_server\",\
|
||||||
\"families\":25,\"logical_series\":1179,\"rendered_series\":3654,\"exemplar_slots\":2310}]}\n"
|
\"families\":26,\"logical_series\":1101,\"rendered_series\":3576,\"exemplar_slots\":2310}]}\n"
|
||||||
));
|
));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
schema_budget(MetricService::AdminApi),
|
schema_budget(MetricService::AdminApi),
|
||||||
Ok(crank_metrics::SchemaBudget {
|
Ok(crank_metrics::SchemaBudget {
|
||||||
logical_series: 6_381,
|
logical_series: 6_303,
|
||||||
rendered_series: 19_611
|
rendered_series: 19_533
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
schema_budget(MetricService::McpServer),
|
schema_budget(MetricService::McpServer),
|
||||||
Ok(crank_metrics::SchemaBudget {
|
Ok(crank_metrics::SchemaBudget {
|
||||||
logical_series: 1_179,
|
logical_series: 1_101,
|
||||||
rendered_series: 3_654
|
rendered_series: 3_576
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -751,7 +751,7 @@ fn service_projection_cache_is_allocated_once() {
|
|||||||
}
|
}
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
metric_schema().len(),
|
metric_schema().len(),
|
||||||
23,
|
26,
|
||||||
"union metadata сохраняет 23 family"
|
"union metadata сохраняет 23 family v1 и три family admission"
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -9,7 +9,8 @@ fn sequence_is_deterministic_and_append_only() {
|
|||||||
assert_eq!(
|
assert_eq!(
|
||||||
first.iter().map(|item| item.version).collect::<Vec<_>>(),
|
first.iter().map(|item| item.version).collect::<Vec<_>>(),
|
||||||
vec![
|
vec![
|
||||||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23
|
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
|
||||||
|
25, 26, 27, 28, 29, 30
|
||||||
]
|
]
|
||||||
);
|
);
|
||||||
assert_eq!(first[0].checksum, "crank-community-baseline-v1");
|
assert_eq!(first[0].checksum, "crank-community-baseline-v1");
|
||||||
|
|||||||
@@ -45,6 +45,8 @@ Logging-handler-срез #107 поверх rc.38/rmcp3.9.0 подключает
|
|||||||
|
|
||||||
Progress/cancel-срез #107 на базе rc.23/rmcp3.9.0 подключает штатный SSE `lifecycle::progress_frame` обеих revisions к сериализации `ProgressNotificationParam`, а legacy `handle_cancelled_notification` — к декодированию `CancelledNotificationParam.request_id`. Локальная projection+restore сохраняет исходные JSON numbers токена/ID и целочисленный u64 progress, включая значения вне i64/exact-f64; message и omissions берутся из SDK. Decoder передаёт SDK только requestId, не валидируя reason/_meta/extensions. Session+credential ownership, bounded queues/slots, transport, auth и modern stream-close cancellation не меняются. Runtime ATDD подтверждает SDK seams отдельно от wire; unit regression проверяет точную числовую форму. Decoder ignore действует только после HTTP admission: `_meta:[]` сохраняет прежний HTTP400/-32020 до SDK decoder. Отдельная HTTP-регрессия проверяет отказ без отмены активного вызова, а допустимый `_meta:{}` с reason/extensions — успешную SDK-отмену. Это частичная миграция params, не завершение #107, feature qualification или production deployment.
|
Progress/cancel-срез #107 на базе rc.23/rmcp3.9.0 подключает штатный SSE `lifecycle::progress_frame` обеих revisions к сериализации `ProgressNotificationParam`, а legacy `handle_cancelled_notification` — к декодированию `CancelledNotificationParam.request_id`. Локальная projection+restore сохраняет исходные JSON numbers токена/ID и целочисленный u64 progress, включая значения вне i64/exact-f64; message и omissions берутся из SDK. Decoder передаёт SDK только requestId, не валидируя reason/_meta/extensions. Session+credential ownership, bounded queues/slots, transport, auth и modern stream-close cancellation не меняются. Runtime ATDD подтверждает SDK seams отдельно от wire; unit regression проверяет точную числовую форму. Decoder ignore действует только после HTTP admission: `_meta:[]` сохраняет прежний HTTP400/-32020 до SDK decoder. Отдельная HTTP-регрессия проверяет отказ без отмены активного вызова, а допустимый `_meta:{}` с reason/extensions — успешную SDK-отмену. Это частичная миграция params, не завершение #107, feature qualification или production deployment.
|
||||||
|
|
||||||
|
Progress-Peer-срез #107 поверх rc.40/rmcp3.9.0 заменяет DTO-only `lifecycle::progress_frame`: действующий `build_app` SSE обеих revisions вызывает request-local `Peer::notify_progress`, потребляет actual SDK outbound notification и передаёт её прежнему SSE consumer. Один endpoint принадлежит body; single-flight send и output1 не расширяют producer queue8/drop-newest и cancellation table256. SDK получает только постоянный внутренний progress token, чтобы его TRACE не раскрывал клиентское значение; после проверки actual output token восстанавливаются исходный string/numeric token и точный u64 progress, а message/omissions остаются SDK output. Глобальные TRACE/application logs не отключаются. Domain Tool не выполняется второй раз: send failure отключает только progress, без retry/fallback. Pending send одновременно poll-ит прежний domain future и cancellation; исходный upstream timeout закрывает bridge без нового deadline budget. Drop body закрывает endpoint, managed owner отменяет и join-ит SDK pump. JSON/no-token/invalid-token/no-carrier не создают endpoint; carried logging и terminal projection остаются прежними. Это перенос outbound progress, не новый HTTP transport/session manager и не завершение #107; full/load/external-client qualification и production не входят в срез.
|
||||||
|
|
||||||
Catalog-change signals/subscriptions-срез #107 на базе rc.24/rmcp3.9.0 использует прежний `protocol/signals.rs` watcher: штатный modern `subscriptions/listen` декодирует notifications через `SubscriptionsListenRequestParams`/`SubscriptionFilter`, а acknowledgment и три list-change notification сериализуются настоящими SDK notification types в `protocol/signals_sdk.rs`. Тонкая входная projection сохраняет прежний запрет explicit null известных filter fields и игнорирование extensions; `_meta` по-прежнему проверяется только HTTP admission до decoder. SDK `NotificationMetaObject` хранит исходный JSON subscriptionId без сужения через RequestId; legacy frames остаются без params, modern ack первым сообщает только true accepted subset. URI-content subscriptions остаются unsupported, bounds32/2048 и64-byte id bound сохранены. Ближайший потребитель уже подключён: действующий `build_app` modern listen SSE и legacy GET SSE после committed catalog changes. HTTP ATDD независимо проверяет SDK execution и wire обеих revisions; прежние signals integration сохраняют Resource/Prompt/Tool delivery, scope, coalescing/recovery. Handwritten filter field DTO и frame builders заменены; fingerprint, watcher timing/queue/drop, auth/session/ownership/TTL/capabilities и transport не меняются. Полный #107, external-client/feature qualification и production deployment этим срезом не завершены.
|
Catalog-change signals/subscriptions-срез #107 на базе rc.24/rmcp3.9.0 использует прежний `protocol/signals.rs` watcher: штатный modern `subscriptions/listen` декодирует notifications через `SubscriptionsListenRequestParams`/`SubscriptionFilter`, а acknowledgment и три list-change notification сериализуются настоящими SDK notification types в `protocol/signals_sdk.rs`. Тонкая входная projection сохраняет прежний запрет explicit null известных filter fields и игнорирование extensions; `_meta` по-прежнему проверяется только HTTP admission до decoder. SDK `NotificationMetaObject` хранит исходный JSON subscriptionId без сужения через RequestId; legacy frames остаются без params, modern ack первым сообщает только true accepted subset. URI-content subscriptions остаются unsupported, bounds32/2048 и64-byte id bound сохранены. Ближайший потребитель уже подключён: действующий `build_app` modern listen SSE и legacy GET SSE после committed catalog changes. HTTP ATDD независимо проверяет SDK execution и wire обеих revisions; прежние signals integration сохраняют Resource/Prompt/Tool delivery, scope, coalescing/recovery. Handwritten filter field DTO и frame builders заменены; fingerprint, watcher timing/queue/drop, auth/session/ownership/TTL/capabilities и transport не меняются. Полный #107, external-client/feature qualification и production deployment этим срезом не завершены.
|
||||||
|
|
||||||
Subscriptions-handler-срез #107 поверх rc.39/rmcp3.9.0 подключает modern `app/dispatch.rs::SubscriptionsListen` к единственному request-owned default `Service::handle_request` в `app/rmcp_subscriptions.rs`. Живой локальный SDK Peer обслуживает только outbound notifications: actual SDK ACK и последовательные `SubscriptionSink` list-change notifications поступают через `app/rmcp_subscriptions_output.rs` в прежнюю очередь4 и SSE consumer. Registry capabilities и SDK requested/candidate/advertised intersection определяют accepted subset; URI subscriptions не включаются. Единственный общий watcher сохраняет baseline до ACK, scoped catalog reads, Retry/Gone, cadence/coalescing и legacy delivery. JSON subscriptionId восстанавливается без числового сужения; SDK final Result/ErrorData потребляется owner, не отправляется новым terminal frame. Закрытие body/отмена до ACK дропает pending watcher и завершает/join-ит SDK pump; permit остаётся у body. Это runtime-перенос действующей подписки, не замена HTTP transport/session и не full/load/external-client qualification всего #107.
|
Subscriptions-handler-срез #107 поверх rc.39/rmcp3.9.0 подключает modern `app/dispatch.rs::SubscriptionsListen` к единственному request-owned default `Service::handle_request` в `app/rmcp_subscriptions.rs`. Живой локальный SDK Peer обслуживает только outbound notifications: actual SDK ACK и последовательные `SubscriptionSink` list-change notifications поступают через `app/rmcp_subscriptions_output.rs` в прежнюю очередь4 и SSE consumer. Registry capabilities и SDK requested/candidate/advertised intersection определяют accepted subset; URI subscriptions не включаются. Единственный общий watcher сохраняет baseline до ACK, scoped catalog reads, Retry/Gone, cadence/coalescing и legacy delivery. JSON subscriptionId восстанавливается без числового сужения; SDK final Result/ErrorData потребляется owner, не отправляется новым terminal frame. Закрытие body/отмена до ACK дропает pending watcher и завершает/join-ит SDK pump; permit остаётся у body. Это runtime-перенос действующей подписки, не замена HTTP transport/session и не full/load/external-client qualification всего #107.
|
||||||
|
|||||||
+12
-6
@@ -167,7 +167,7 @@ scrape_configs:
|
|||||||
credentials_file: /run/secrets/crank_metrics_token
|
credentials_file: /run/secrets/crank_metrics_token
|
||||||
```
|
```
|
||||||
|
|
||||||
Семейства первой версии:
|
Семейства текущего registry:
|
||||||
|
|
||||||
- `crank_http_requests_total`, `crank_http_request_duration_seconds`,
|
- `crank_http_requests_total`, `crank_http_request_duration_seconds`,
|
||||||
`crank_http_inflight`;
|
`crank_http_inflight`;
|
||||||
@@ -178,6 +178,7 @@ scrape_configs:
|
|||||||
- `crank_upstream_requests_total`,
|
- `crank_upstream_requests_total`,
|
||||||
`crank_upstream_request_duration_seconds`;
|
`crank_upstream_request_duration_seconds`;
|
||||||
- `crank_runtime_inflight`, `crank_runtime_limit_rejections_total`,
|
- `crank_runtime_inflight`, `crank_runtime_limit_rejections_total`,
|
||||||
|
`crank_runtime_admission_rejections_total`,
|
||||||
`crank_runtime_admission_queue_wait_seconds`,
|
`crank_runtime_admission_queue_wait_seconds`,
|
||||||
`crank_runtime_admission_oldest_waiting_seconds`,
|
`crank_runtime_admission_oldest_waiting_seconds`,
|
||||||
`crank_runtime_cache_total`, `crank_idempotency_total`,
|
`crank_runtime_cache_total`, `crank_idempotency_total`,
|
||||||
@@ -218,12 +219,17 @@ freshness в `1`. Прикладные ошибки JSON-RPC и
|
|||||||
завершает соответствующее измерение закрытым исходом `aborted`, поэтому
|
завершает соответствующее измерение закрытым исходом `aborted`, поэтому
|
||||||
фактически начатый вызов не исчезает из показателей.
|
фактически начатый вызов не исчезает из показателей.
|
||||||
|
|
||||||
|
`crank_runtime_limit_rejections_total` сохраняет только product label `stage`
|
||||||
|
(`concurrency`, `rate_limit`, `mcp_stream`). Отказы scoped admission учитываются
|
||||||
|
отдельно в `crank_runtime_admission_rejections_total` с закрытыми labels
|
||||||
|
`reason` и `scope_kind` и не инкрементируют прежний счётчик.
|
||||||
|
|
||||||
Buckets длительности фиксированы кодом:
|
Buckets длительности фиксированы кодом:
|
||||||
`0.005`, `0.01`, `0.025`, `0.05`, `0.1`, `0.25`, `0.5`, `1`, `2.5`, `5`,
|
`0.005`, `0.01`, `0.025`, `0.05`, `0.1`, `0.25`, `0.5`, `1`, `2.5`, `5`,
|
||||||
`10`, `30`, `60` секунд. Это пока техническая шкала, а не SLO. Registry v2
|
`10`, `30`, `60` секунд. Это пока техническая шкала, а не SLO. Registry v2
|
||||||
(`schemas/metrics-registry-v2.json`, генерируется Rust descriptor table,
|
(`schemas/metrics-registry-v2.json`, генерируется Rust descriptor table,
|
||||||
`schema_version=2`) содержит те же 23 family и фиксирует допустимые
|
`schema_version=2`) сохраняет 23 семейства v1 и добавляет три семейства admission.
|
||||||
HTTP-идентичности как единственное typed перечисление route+owners: union 91,
|
Он фиксирует HTTP-идентичности как единое typed перечисление route+owners: union 91,
|
||||||
admin-проекция 86, mcp-проекция 8, общие ровно `/health`, `/ready`,
|
admin-проекция 86, mcp-проекция 8, общие ровно `/health`, `/ready`,
|
||||||
`unmatched`. Тринадцать Resource-шаблонов
|
`unmatched`. Тринадцать Resource-шаблонов
|
||||||
(`/api/admin/workspaces/{workspace_id}/resources` и его `{resource_id}`,
|
(`/api/admin/workspaces/{workspace_id}/resources` и его `{resource_id}`,
|
||||||
@@ -237,10 +243,10 @@ Prompt-шаблонов (`.../prompts`, `.../prompts/import`, `.../prompts/{prom
|
|||||||
|
|
||||||
Бюджет кардинальности считается **на процесс**, а не на union:
|
Бюджет кардинальности считается **на процесс**, а не на union:
|
||||||
|
|
||||||
- admin-api — 15 family, 6 285 logical, 19 515 rendered, 12 348 exemplar slots;
|
- admin-api — 18 family, 6 303 logical, 19 533 rendered, 12 348 exemplar slots;
|
||||||
- mcp-server — 23 family, 1 083 logical, 3 558 rendered, 2 310 exemplar slots.
|
- mcp-server — 26 family, 1 101 logical, 3 576 rendered, 2 310 exemplar slots.
|
||||||
|
|
||||||
Hard ceilings — 6 285 logical / 19 515 rendered / 12 348 exemplar
|
Hard ceilings — 6 381 logical / 19 611 rendered / 12 348 exemplar
|
||||||
slots на процесс и 8 388 608 bytes (8 MiB) на готовый exposition. Ранее
|
slots на процесс и 8 388 608 bytes (8 MiB) на готовый exposition. Ранее
|
||||||
logical ceiling поднимали с 5 563 до 5 585 явным решением владельца только для
|
logical ceiling поднимали с 5 563 до 5 585 явным решением владельца только для
|
||||||
регистрации уже существующего revoke-маршрута Resource, затем для трёх адресов
|
регистрации уже существующего revoke-маршрута Resource, затем для трёх адресов
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
{"schema_version":2,"limits":{"max_families":128,"max_product_labels_per_family":4,"max_logical_series":6381,"max_rendered_series":19611,"max_exemplar_slots":12348,"max_exposition_bytes":8388608},"global_labels":[{"name":"service","class":"process_constant","domain":["admin-api","mcp-server"]},{"name":"version","class":"process_constant","domain":["validated_release_identity"]},{"name":"environment","class":"process_constant","domain":["validated_startup_value"]}],"http_routes":[{"route":"/api/admin/capabilities","processes":["admin_api"]},{"route":"/api/admin/workspaces","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/agents","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/agents/tool-search/preview","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/agents/{agent_id}","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/archive","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/bindings","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/platform-api-keys","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/platform-api-keys/{key_id}","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/platform-api-keys/{key_id}/revoke","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/publish","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/unpublish","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/versions/{version}","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/approvals","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/approvals/{approval_id}","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/approvals/{approval_id}/approve","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/approvals/{approval_id}/deny","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/auth-profiles","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/auth-profiles/{auth_profile_id}","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/export","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/imports/openapi/plans/{plan_id}","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/imports/openapi/preview","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/imports/openapi/{job_id}/create","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/imports/openapi/{job_id}/plans","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/imports/openapi/{plan_id}/apply","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/logs","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/logs/export.csv","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/logs/{log_id}","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/onboarding","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/onboarding/events","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/onboarding/import-context","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/onboarding/reset-selection","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/onboarding/select-draft","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/operations","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/operations/analyze-quality","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/operations/import","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/operations/{operation_id}","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/archive","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/drafts/generate","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/export","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/publish","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/samples/input-json","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/samples/output-json","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/test-runs","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/Line truncated
|
{"schema_version":2,"limits":{"max_families":128,"max_product_labels_per_family":4,"max_logical_series":6381,"max_rendered_series":19611,"max_exemplar_slots":12348,"max_exposition_bytes":8388608},"global_labels":[{"name":"service","class":"process_constant","domain":["admin-api","mcp-server"]},{"name":"version","class":"process_constant","domain":["validated_release_identity"]},{"name":"environment","class":"process_constant","domain":["validated_startup_value"]}],"http_routes":[{"route":"/api/admin/capabilities","processes":["admin_api"]},{"route":"/api/admin/workspaces","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/agents","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/agents/tool-search/preview","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/agents/{agent_id}","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/archive","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/bindings","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/platform-api-keys","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/platform-api-keys/{key_id}","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/platform-api-keys/{key_id}/revoke","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/publish","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/unpublish","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/agents/{agent_id}/versions/{version}","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/approvals","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/approvals/{approval_id}","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/approvals/{approval_id}/approve","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/approvals/{approval_id}/deny","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/auth-profiles","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/auth-profiles/{auth_profile_id}","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/export","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/imports/openapi/plans/{plan_id}","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/imports/openapi/preview","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/imports/openapi/{job_id}/create","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/imports/openapi/{job_id}/plans","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/imports/openapi/{plan_id}/apply","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/logs","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/logs/export.csv","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/logs/{log_id}","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/onboarding","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/onboarding/events","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/onboarding/import-context","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/onboarding/reset-selection","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/onboarding/select-draft","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/operations","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/operations/analyze-quality","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/operations/import","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/operations/{operation_id}","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/archive","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/drafts/generate","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/export","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/publish","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/samples/input-json","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/samples/output-json","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/operations/{operation_id}/test-runs","processes":["admin_api"]},{"route":"/api/admin/workspaces/{workspace_id}/Line truncated
|
||||||
@@ -156,11 +156,10 @@ class DeployPolicyTests(unittest.TestCase):
|
|||||||
self.assertIn("default: none", block)
|
self.assertIn("default: none", block)
|
||||||
self.assertIn("required: true", block)
|
self.assertIn("required: true", block)
|
||||||
|
|
||||||
def test_push_main_source_ci_stays_enabled(self):
|
def test_full_ci_targets_main_pull_requests(self):
|
||||||
self.assertRegex(
|
workflow = workflow_text()
|
||||||
workflow_text(),
|
self.assertRegex(workflow, r"(?m)^ pull_request:\n branches: \[main\]$")
|
||||||
r"(?m)^ push:\n branches:\n - main$",
|
self.assertNotRegex(workflow, r"(?m)^ push:")
|
||||||
)
|
|
||||||
|
|
||||||
def test_deploy_requires_successful_required_checks(self):
|
def test_deploy_requires_successful_required_checks(self):
|
||||||
deploy = job_block("deploy")
|
deploy = job_block("deploy")
|
||||||
|
|||||||
@@ -112,7 +112,7 @@ class WorkflowScopeTests(unittest.TestCase):
|
|||||||
def test_only_four_heavy_rust_steps_are_skippable(self):
|
def test_only_four_heavy_rust_steps_are_skippable(self):
|
||||||
workflow = WORKFLOW.read_text(encoding="utf-8")
|
workflow = WORKFLOW.read_text(encoding="utf-8")
|
||||||
self.assertIn("run: python3 scripts/ci-release-tooling-scope.py", workflow)
|
self.assertIn("run: python3 scripts/ci-release-tooling-scope.py", workflow)
|
||||||
self.assertIn("FORCE_FULL: ${{ inputs.validation_level == 'feature' || contains(gitea.event.pull_request.labels.*.name, 'feature-ready') }}", workflow)
|
self.assertIn("FORCE_FULL: ${{ gitea.event_name == 'pull_request' || inputs.validation_level == 'feature' }}", workflow)
|
||||||
conditional = "if: steps.release_tooling.outputs.ci_only != 'true'"
|
conditional = "if: steps.release_tooling.outputs.ci_only != 'true'"
|
||||||
for name in (
|
for name in (
|
||||||
"Check typed runtime configuration contract",
|
"Check typed runtime configuration contract",
|
||||||
|
|||||||
Reference in new issue
Block a user