Исправления этапа 1: редактирование агента, исход выполнения и пул соединений #83
No files matched your search
@@ -0,0 +1 @@
|
||||
docs/epic-1-completion/evidence/*.patch -whitespace
|
||||
@@ -38,6 +38,11 @@ npx playwright test
|
||||
[`docs/capability-baseline/manifest.json`](./docs/capability-baseline/manifest.json),
|
||||
sanitized results и SHA-256. Нельзя вручную объявлять pass для failed, flaky,
|
||||
skipped, not-run или manual-only evidence.
|
||||
- Для записи результатов этапа и разделения исторического capability baseline
|
||||
и текущего completion evidence следуйте
|
||||
[правилам evidence разработки](./docs/development-evidence.md). Перед этапом
|
||||
фиксируйте полный clean Git baseline; проверенную реализацию указывайте
|
||||
отдельной ревизией.
|
||||
- Не добавляйте секреты, токены, приватные адреса и локальные настройки.
|
||||
- Не коммитьте `AGENTS.md`, `TASKS.md`, `.env` и временные файлы.
|
||||
- Для изменений SQL-запросов обновляйте `.sqlx`, если это требуется SQLx.
|
||||
|
||||
Generated
-2
@@ -3537,8 +3537,6 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "sqlx-core"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "05b44e85bf579a8eeb4ceaa77a3a523baf2bf0e9bac7e40f405d537b5d2d5ccb"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"bytes",
|
||||
|
||||
@@ -18,8 +18,12 @@ members = [
|
||||
"crates/crank-adapter-rest",
|
||||
"crates/crank-artifacts",
|
||||
]
|
||||
exclude = ["vendor/sqlx-core"]
|
||||
resolver = "3"
|
||||
|
||||
[patch.crates-io]
|
||||
sqlx-core = { path = "vendor/sqlx-core" }
|
||||
|
||||
[workspace.package]
|
||||
edition = "2024"
|
||||
license = "AGPL-3.0-only"
|
||||
|
||||
@@ -3,6 +3,7 @@ FROM rust:1.96.1-bookworm AS builder
|
||||
WORKDIR /app
|
||||
|
||||
COPY Cargo.toml Cargo.lock ./
|
||||
COPY vendor ./vendor
|
||||
COPY .sqlx ./.sqlx
|
||||
COPY apps ./apps
|
||||
COPY crates ./crates
|
||||
|
||||
@@ -5,9 +5,8 @@ use crank_core::{
|
||||
ToolAccessMode, ToolSelectionPolicy, UsagePeriod, WorkspaceId, search_tool_catalog,
|
||||
};
|
||||
use crank_registry::{
|
||||
AgentStateExpectation, AgentVersionRecord, CreateAgentDraftVersionRequest, CreateAgentRequest,
|
||||
PublishAgentRequest, SaveAgentCatalogConfigRequest, UpdateAgentSummaryRequest, UsageBucket,
|
||||
UsageQuery,
|
||||
AgentStateExpectation, AgentVersionRecord, CreateAgentRequest, PublishAgentRequest,
|
||||
SaveAgentCatalogConfigRequest, UpdateAgentSummaryRequest, UsageBucket, UsageQuery,
|
||||
};
|
||||
use serde_json::json;
|
||||
use sha2::{Digest, Sha256};
|
||||
@@ -471,8 +470,9 @@ impl AdminService {
|
||||
payload: AgentCatalogPayload,
|
||||
expected_state: Option<&AgentStateExpectation>,
|
||||
) -> Result<AgentVersionRecord, ApiError> {
|
||||
let agent = self.get_agent(workspace_id, agent_id).await?;
|
||||
let current_version = self
|
||||
.ensure_editable_agent_version(workspace_id, agent_id)
|
||||
.get_agent_version(workspace_id, agent_id, agent.current_draft_version)
|
||||
.await?;
|
||||
let (payload, requested_policy) = payload.into_parts();
|
||||
let bindings = payload
|
||||
@@ -492,8 +492,9 @@ impl AdminService {
|
||||
.unwrap_or_else(|| current_version.snapshot.tool_selection_policy.clone());
|
||||
validate_tool_selection_policy(&tool_selection_policy, &bindings)?;
|
||||
|
||||
self.registry
|
||||
.save_agent_catalog_config(SaveAgentCatalogConfigRequest {
|
||||
let saved_version = self
|
||||
.registry
|
||||
.save_agent_catalog_config_editable(SaveAgentCatalogConfigRequest {
|
||||
workspace_id,
|
||||
agent_id,
|
||||
agent_version: current_version.version,
|
||||
@@ -505,47 +506,12 @@ impl AdminService {
|
||||
info!(
|
||||
name: "admin.agent.bindings_saved",
|
||||
agent_id = %agent_id.as_str(),
|
||||
version = current_version.version,
|
||||
version = saved_version,
|
||||
binding_count = bindings.len(),
|
||||
"agent bindings saved"
|
||||
);
|
||||
|
||||
self.get_agent_version(workspace_id, agent_id, current_version.version)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn ensure_editable_agent_version(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
agent_id: &AgentId,
|
||||
) -> Result<AgentVersionRecord, ApiError> {
|
||||
let agent = self.get_agent(workspace_id, agent_id).await?;
|
||||
let current = self
|
||||
.get_agent_version(workspace_id, agent_id, agent.current_draft_version)
|
||||
.await?;
|
||||
if agent.latest_published_version != Some(agent.current_draft_version) {
|
||||
return Ok(current);
|
||||
}
|
||||
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let draft = AgentVersion {
|
||||
agent_id: agent_id.clone(),
|
||||
version: current.version + 1,
|
||||
status: AgentStatus::Draft,
|
||||
instructions: current.snapshot.instructions.clone(),
|
||||
tool_selection_policy: current.snapshot.tool_selection_policy.clone(),
|
||||
created_at: now,
|
||||
};
|
||||
self.registry
|
||||
.create_agent_draft_version(CreateAgentDraftVersionRequest {
|
||||
workspace_id,
|
||||
agent_id,
|
||||
version: &draft,
|
||||
bindings: ¤t.bindings,
|
||||
updated_at: &now,
|
||||
})
|
||||
.await?;
|
||||
self.get_agent_version(workspace_id, agent_id, draft.version)
|
||||
self.get_agent_version(workspace_id, agent_id, saved_version)
|
||||
.await
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
mod integration {
|
||||
mod agent_catalog;
|
||||
mod agent_catalog_edit;
|
||||
mod auth_rate_limit;
|
||||
mod common;
|
||||
mod community_access_usage;
|
||||
|
||||
@@ -0,0 +1,889 @@
|
||||
use super::common::*;
|
||||
|
||||
use crank_core::{Workspace, WorkspaceId, WorkspaceStatus};
|
||||
use crank_registry::{CreateWorkspaceRequest, PostgresRegistry};
|
||||
use serde_json::{Value, json};
|
||||
use serial_test::serial;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
const DEFAULT_WORKSPACE_ID: &str = "ws_default";
|
||||
|
||||
fn binding(operation_id: &str, tool_name: &str, tool_title: &str) -> Value {
|
||||
json!({
|
||||
"operation_id": operation_id,
|
||||
"operation_version": 1,
|
||||
"tool_name": tool_name,
|
||||
"tool_title": tool_title,
|
||||
"tool_description_override": null,
|
||||
"enabled": true
|
||||
})
|
||||
}
|
||||
|
||||
async fn create_draft_operation(
|
||||
client: &reqwest::Client,
|
||||
base_url: &TestServer,
|
||||
upstream: &str,
|
||||
name: &str,
|
||||
) -> String {
|
||||
let operation = assert_success_json(
|
||||
client
|
||||
.post(format!("{base_url}/operations"))
|
||||
.json(&test_operation_payload(upstream, name))
|
||||
.send()
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
operation["operation_id"].as_str().unwrap().to_owned()
|
||||
}
|
||||
|
||||
async fn create_published_operation(
|
||||
client: &reqwest::Client,
|
||||
base_url: &TestServer,
|
||||
upstream: &str,
|
||||
name: &str,
|
||||
) -> String {
|
||||
let operation_id = create_draft_operation(client, base_url, upstream, name).await;
|
||||
let etag = operation_etag(client, base_url, &operation_id).await;
|
||||
assert_success_json(
|
||||
client
|
||||
.post(format!("{base_url}/operations/{operation_id}/publish"))
|
||||
.header(reqwest::header::IF_MATCH, etag)
|
||||
.json(&json!({ "version": 1 }))
|
||||
.send()
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
operation_id
|
||||
}
|
||||
|
||||
async fn create_published_agent(
|
||||
client: &reqwest::Client,
|
||||
base_url: &TestServer,
|
||||
slug: &str,
|
||||
operation_id: &str,
|
||||
tool_name: &str,
|
||||
) -> (String, Value) {
|
||||
let agent = assert_success_json(
|
||||
client
|
||||
.post(format!("{base_url}/agents"))
|
||||
.json(&json!({
|
||||
"slug": slug,
|
||||
"display_name": slug,
|
||||
"description": "agent catalog edit fixture",
|
||||
"instructions": { "system_prompt": "Use only published bindings" },
|
||||
"tool_selection_policy": {}
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
let agent_id = agent["agent_id"].as_str().unwrap().to_owned();
|
||||
|
||||
let etag = agent_etag(client, base_url, &agent_id).await;
|
||||
assert_success_json(
|
||||
client
|
||||
.post(format!("{base_url}/agents/{agent_id}/bindings"))
|
||||
.header(reqwest::header::IF_MATCH, etag)
|
||||
.json(&json!([binding(operation_id, tool_name, "Base Tool")]))
|
||||
.send()
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
|
||||
let etag = agent_etag(client, base_url, &agent_id).await;
|
||||
assert_success_json(
|
||||
client
|
||||
.post(format!("{base_url}/agents/{agent_id}/publish"))
|
||||
.header(reqwest::header::IF_MATCH, etag)
|
||||
.json(&json!({ "version": 1 }))
|
||||
.send()
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
|
||||
let published_v1 = assert_success_json(
|
||||
client
|
||||
.get(format!("{base_url}/agents/{agent_id}/versions/1"))
|
||||
.send()
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
|
||||
(agent_id, published_v1)
|
||||
}
|
||||
|
||||
async fn agent_version_count(db: &PostgresRegistry, agent_id: &str) -> i64 {
|
||||
sqlx::query_scalar("select count(*) from agent_versions where agent_id = $1")
|
||||
.bind(agent_id)
|
||||
.fetch_one(db.pool())
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
async fn assert_no_durable_draft(
|
||||
client: &reqwest::Client,
|
||||
db: &PostgresRegistry,
|
||||
base_url: &TestServer,
|
||||
agent_id: &str,
|
||||
published_v1: &Value,
|
||||
) {
|
||||
let summary = assert_success_json(
|
||||
client
|
||||
.get(format!("{base_url}/agents/{agent_id}"))
|
||||
.send()
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
summary["current_draft_version"], 1,
|
||||
"a rejected edit must not fork a Draft Version: {summary}"
|
||||
);
|
||||
assert_eq!(summary["latest_published_version"], 1, "{summary}");
|
||||
assert_eq!(summary["status"], "published", "{summary}");
|
||||
assert_eq!(
|
||||
agent_version_count(db, agent_id).await,
|
||||
1,
|
||||
"a rejected edit must not persist a new Agent Version row"
|
||||
);
|
||||
|
||||
let published_after = assert_success_json(
|
||||
client
|
||||
.get(format!("{base_url}/agents/{agent_id}/versions/1"))
|
||||
.send()
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
&published_after, published_v1,
|
||||
"the Published snapshot and its bindings must stay unchanged after a rejected edit"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[serial]
|
||||
async fn published_agent_first_edit_forks_one_draft_and_keeps_published_snapshot() {
|
||||
let registry = test_registry().await;
|
||||
let db = registry.clone();
|
||||
let storage_root = test_storage_root("agent_catalog_edit_first");
|
||||
let upstream_base_url = spawn_upstream_server().await;
|
||||
let base_url = spawn_admin_api(build_test_app(registry, storage_root)).await;
|
||||
let client = authorized_client(&base_url).await;
|
||||
|
||||
let operation_id =
|
||||
create_published_operation(&client, &base_url, &upstream_base_url, "edit_first_tool").await;
|
||||
let (agent_id, published_v1) = create_published_agent(
|
||||
&client,
|
||||
&base_url,
|
||||
"edit-first",
|
||||
&operation_id,
|
||||
"edit_first_tool",
|
||||
)
|
||||
.await;
|
||||
|
||||
let summary_before = assert_success_json(
|
||||
client
|
||||
.get(format!("{base_url}/agents/{agent_id}"))
|
||||
.send()
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(summary_before["current_draft_version"], 1);
|
||||
assert_eq!(summary_before["latest_published_version"], 1);
|
||||
assert_eq!(summary_before["status"], "published");
|
||||
|
||||
let desired_policy = json!({
|
||||
"mode": "search",
|
||||
"groups": [{
|
||||
"id": "crm-group",
|
||||
"name": "CRM",
|
||||
"description": "CRM tools",
|
||||
"tool_names": ["edit_first_tool"]
|
||||
}],
|
||||
"search": { "max_results": 5 }
|
||||
});
|
||||
|
||||
let edit_etag = agent_etag(&client, &base_url, &agent_id).await;
|
||||
let response = client
|
||||
.post(format!("{base_url}/agents/{agent_id}/bindings"))
|
||||
.header(reqwest::header::IF_MATCH, edit_etag)
|
||||
.json(&json!({
|
||||
"bindings": [binding(&operation_id, "edit_first_tool", "Edited Tool")],
|
||||
"tool_selection_policy": desired_policy
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let status = response.status();
|
||||
let body = response.json::<Value>().await.unwrap();
|
||||
assert_eq!(
|
||||
status,
|
||||
reqwest::StatusCode::OK,
|
||||
"the first edit of a Published Agent must fork and save under the original If-Match: {body}"
|
||||
);
|
||||
assert_eq!(body["version"], 2, "{body}");
|
||||
|
||||
let summary_after = assert_success_json(
|
||||
client
|
||||
.get(format!("{base_url}/agents/{agent_id}"))
|
||||
.send()
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(summary_after["current_draft_version"], 2, "{summary_after}");
|
||||
assert_eq!(
|
||||
summary_after["latest_published_version"], 1,
|
||||
"{summary_after}"
|
||||
);
|
||||
assert_eq!(summary_after["status"], "published", "{summary_after}");
|
||||
|
||||
assert_eq!(
|
||||
agent_version_count(&db, &agent_id).await,
|
||||
2,
|
||||
"the first edit must create exactly one additional Draft Version"
|
||||
);
|
||||
|
||||
let draft = assert_success_json(
|
||||
client
|
||||
.get(format!("{base_url}/agents/{agent_id}/versions/2"))
|
||||
.send()
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(draft["status"], "draft", "{draft}");
|
||||
assert_eq!(
|
||||
draft["snapshot"]["instructions"],
|
||||
published_v1["snapshot"]["instructions"]
|
||||
);
|
||||
assert_eq!(draft["bindings"].as_array().unwrap().len(), 1, "{draft}");
|
||||
assert_eq!(draft["bindings"][0]["tool_title"], "Edited Tool", "{draft}");
|
||||
assert_eq!(
|
||||
draft["snapshot"]["tool_selection_policy"]["mode"], "search",
|
||||
"{draft}"
|
||||
);
|
||||
assert_eq!(
|
||||
draft["snapshot"]["tool_selection_policy"]["search"]["max_results"], 5,
|
||||
"{draft}"
|
||||
);
|
||||
|
||||
let published_after = assert_success_json(
|
||||
client
|
||||
.get(format!("{base_url}/agents/{agent_id}/versions/1"))
|
||||
.send()
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
published_after, published_v1,
|
||||
"the Published v1 snapshot must not change when the Draft is forked"
|
||||
);
|
||||
|
||||
let next_etag = agent_etag(&client, &base_url, &agent_id).await;
|
||||
let second_response = client
|
||||
.post(format!("{base_url}/agents/{agent_id}/bindings"))
|
||||
.header(reqwest::header::IF_MATCH, next_etag)
|
||||
.json(&json!({
|
||||
"bindings": [binding(&operation_id, "edit_first_tool", "Edited Again")],
|
||||
"tool_selection_policy": desired_policy
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let second_status = second_response.status();
|
||||
let second_body = second_response.text().await.unwrap();
|
||||
assert_eq!(
|
||||
second_status,
|
||||
reqwest::StatusCode::OK,
|
||||
"a subsequent valid edit on the Draft must succeed: {second_body}"
|
||||
);
|
||||
assert_eq!(
|
||||
agent_version_count(&db, &agent_id).await,
|
||||
2,
|
||||
"a subsequent valid edit must stay on the existing Draft v2"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[serial]
|
||||
async fn rejected_invalid_policy_leaves_no_durable_draft() {
|
||||
let registry = test_registry().await;
|
||||
let db = registry.clone();
|
||||
let storage_root = test_storage_root("agent_catalog_edit_invalid_policy");
|
||||
let upstream_base_url = spawn_upstream_server().await;
|
||||
let base_url = spawn_admin_api(build_test_app(registry, storage_root)).await;
|
||||
let client = authorized_client(&base_url).await;
|
||||
|
||||
let operation_id =
|
||||
create_published_operation(&client, &base_url, &upstream_base_url, "edit_policy_tool")
|
||||
.await;
|
||||
let (agent_id, published_v1) = create_published_agent(
|
||||
&client,
|
||||
&base_url,
|
||||
"edit-policy",
|
||||
&operation_id,
|
||||
"edit_policy_tool",
|
||||
)
|
||||
.await;
|
||||
|
||||
let etag = agent_etag(&client, &base_url, &agent_id).await;
|
||||
let response = client
|
||||
.post(format!("{base_url}/agents/{agent_id}/bindings"))
|
||||
.header(reqwest::header::IF_MATCH, etag)
|
||||
.json(&json!({
|
||||
"bindings": [],
|
||||
"tool_selection_policy": {
|
||||
"mode": "direct",
|
||||
"groups": [{
|
||||
"id": "group-1",
|
||||
"name": "Group",
|
||||
"description": "groups require search mode",
|
||||
"tool_names": []
|
||||
}]
|
||||
}
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let status = response.status();
|
||||
let body = response.text().await.unwrap();
|
||||
assert_eq!(
|
||||
status,
|
||||
reqwest::StatusCode::BAD_REQUEST,
|
||||
"a grouping policy in direct mode must be rejected: {body}"
|
||||
);
|
||||
|
||||
assert_no_durable_draft(&client, &db, &base_url, &agent_id, &published_v1).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[serial]
|
||||
async fn rejected_unpublished_operation_leaves_no_durable_draft() {
|
||||
let registry = test_registry().await;
|
||||
let db = registry.clone();
|
||||
let storage_root = test_storage_root("agent_catalog_edit_draft_op");
|
||||
let upstream_base_url = spawn_upstream_server().await;
|
||||
let base_url = spawn_admin_api(build_test_app(registry, storage_root)).await;
|
||||
let client = authorized_client(&base_url).await;
|
||||
|
||||
let live_operation =
|
||||
create_published_operation(&client, &base_url, &upstream_base_url, "edit_live_tool").await;
|
||||
let (agent_id, published_v1) = create_published_agent(
|
||||
&client,
|
||||
&base_url,
|
||||
"edit-draft-op",
|
||||
&live_operation,
|
||||
"edit_live_tool",
|
||||
)
|
||||
.await;
|
||||
|
||||
let draft_operation =
|
||||
create_draft_operation(&client, &base_url, &upstream_base_url, "edit_draft_tool").await;
|
||||
|
||||
let etag = agent_etag(&client, &base_url, &agent_id).await;
|
||||
let response = client
|
||||
.post(format!("{base_url}/agents/{agent_id}/bindings"))
|
||||
.header(reqwest::header::IF_MATCH, etag)
|
||||
.json(&json!([binding(
|
||||
&draft_operation,
|
||||
"edit_draft_tool",
|
||||
"Draft Tool"
|
||||
)]))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let status = response.status();
|
||||
let body = response.text().await.unwrap();
|
||||
assert_eq!(
|
||||
status,
|
||||
reqwest::StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"binding an unpublished Operation must be rejected: {body}"
|
||||
);
|
||||
let body: Value = serde_json::from_str(&body).unwrap();
|
||||
assert_eq!(
|
||||
body["error"]["code"], "agent_binding_not_published",
|
||||
"{body}"
|
||||
);
|
||||
|
||||
assert_no_durable_draft(&client, &db, &base_url, &agent_id, &published_v1).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[serial]
|
||||
async fn rejected_archived_operation_leaves_no_durable_draft() {
|
||||
let registry = test_registry().await;
|
||||
let db = registry.clone();
|
||||
let storage_root = test_storage_root("agent_catalog_edit_archived_op");
|
||||
let upstream_base_url = spawn_upstream_server().await;
|
||||
let base_url = spawn_admin_api(build_test_app(registry, storage_root)).await;
|
||||
let client = authorized_client(&base_url).await;
|
||||
|
||||
let live_operation = create_published_operation(
|
||||
&client,
|
||||
&base_url,
|
||||
&upstream_base_url,
|
||||
"edit_live_tool_arch",
|
||||
)
|
||||
.await;
|
||||
let (agent_id, published_v1) = create_published_agent(
|
||||
&client,
|
||||
&base_url,
|
||||
"edit-archived-op",
|
||||
&live_operation,
|
||||
"edit_live_tool_arch",
|
||||
)
|
||||
.await;
|
||||
|
||||
let archived_operation =
|
||||
create_published_operation(&client, &base_url, &upstream_base_url, "edit_archived_tool")
|
||||
.await;
|
||||
let operation_etag = operation_etag(&client, &base_url, &archived_operation).await;
|
||||
let archived = client
|
||||
.post(format!(
|
||||
"{base_url}/operations/{archived_operation}/archive"
|
||||
))
|
||||
.header(reqwest::header::IF_MATCH, operation_etag)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let archived_status = archived.status();
|
||||
let archived_body = archived.text().await.unwrap();
|
||||
assert!(archived_status.is_success(), "{archived_body}");
|
||||
|
||||
let etag = agent_etag(&client, &base_url, &agent_id).await;
|
||||
let response = client
|
||||
.post(format!("{base_url}/agents/{agent_id}/bindings"))
|
||||
.header(reqwest::header::IF_MATCH, etag)
|
||||
.json(&json!([binding(
|
||||
&archived_operation,
|
||||
"edit_archived_tool",
|
||||
"Archived Tool"
|
||||
)]))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let status = response.status();
|
||||
let body = response.text().await.unwrap();
|
||||
assert_eq!(
|
||||
status,
|
||||
reqwest::StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"binding an archived Operation must be rejected: {body}"
|
||||
);
|
||||
let body: Value = serde_json::from_str(&body).unwrap();
|
||||
assert_eq!(
|
||||
body["error"]["code"], "agent_binding_archived_operation",
|
||||
"{body}"
|
||||
);
|
||||
|
||||
assert_no_durable_draft(&client, &db, &base_url, &agent_id, &published_v1).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[serial]
|
||||
async fn rejected_foreign_operation_leaves_no_durable_draft() {
|
||||
let registry = test_registry().await;
|
||||
let db = registry.clone();
|
||||
let storage_root = test_storage_root("agent_catalog_edit_foreign_op");
|
||||
let upstream_base_url = spawn_upstream_server().await;
|
||||
let base_url = spawn_admin_api(build_test_app(registry.clone(), storage_root)).await;
|
||||
let client = authorized_client(&base_url).await;
|
||||
|
||||
let live_operation = create_published_operation(
|
||||
&client,
|
||||
&base_url,
|
||||
&upstream_base_url,
|
||||
"edit_live_tool_foreign",
|
||||
)
|
||||
.await;
|
||||
let (agent_id, published_v1) = create_published_agent(
|
||||
&client,
|
||||
&base_url,
|
||||
"edit-foreign-op",
|
||||
&live_operation,
|
||||
"edit_live_tool_foreign",
|
||||
)
|
||||
.await;
|
||||
|
||||
let foreign_workspace = WorkspaceId::new("ws_agent_edit_foreign");
|
||||
let now = OffsetDateTime::now_utc();
|
||||
db.create_workspace(CreateWorkspaceRequest {
|
||||
workspace: &Workspace {
|
||||
id: foreign_workspace.clone(),
|
||||
slug: "agent-edit-foreign".to_owned(),
|
||||
display_name: "Agent Edit Foreign".to_owned(),
|
||||
status: WorkspaceStatus::Active,
|
||||
settings: json!({}),
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let foreign_service = test_service(
|
||||
db.clone(),
|
||||
test_storage_root("agent_catalog_edit_foreign_service"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let foreign_operation = foreign_service
|
||||
.create_operation(
|
||||
&foreign_workspace,
|
||||
test_operation_payload(&upstream_base_url, "edit_foreign_tool"),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let foreign_operation_id = foreign_operation.operation_id;
|
||||
|
||||
let etag = agent_etag(&client, &base_url, &agent_id).await;
|
||||
let response = client
|
||||
.post(format!("{base_url}/agents/{agent_id}/bindings"))
|
||||
.header(reqwest::header::IF_MATCH, etag)
|
||||
.json(&json!([binding(
|
||||
&foreign_operation_id,
|
||||
"edit_foreign_tool",
|
||||
"Foreign Tool"
|
||||
)]))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let status = response.status();
|
||||
let body = response.text().await.unwrap();
|
||||
assert_eq!(
|
||||
status,
|
||||
reqwest::StatusCode::NOT_FOUND,
|
||||
"binding an Operation from another workspace must be rejected: {body}"
|
||||
);
|
||||
let body: Value = serde_json::from_str(&body).unwrap();
|
||||
assert_eq!(
|
||||
body["error"]["code"], "agent_binding_scope_denied",
|
||||
"{body}"
|
||||
);
|
||||
|
||||
assert_no_durable_draft(&client, &db, &base_url, &agent_id, &published_v1).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[serial]
|
||||
async fn concurrent_first_edits_with_same_etag_have_one_winner() {
|
||||
let registry = test_registry().await;
|
||||
let db = registry.clone();
|
||||
let storage_root = test_storage_root("agent_catalog_edit_concurrent");
|
||||
let upstream_base_url = spawn_upstream_server().await;
|
||||
let base_url = spawn_admin_api(build_test_app(registry, storage_root)).await;
|
||||
let client = authorized_client(&base_url).await;
|
||||
|
||||
let operation_id =
|
||||
create_published_operation(&client, &base_url, &upstream_base_url, "edit_race_tool").await;
|
||||
let (agent_id, published_v1) = create_published_agent(
|
||||
&client,
|
||||
&base_url,
|
||||
"edit-race",
|
||||
&operation_id,
|
||||
"edit_race_tool",
|
||||
)
|
||||
.await;
|
||||
|
||||
// Single original precondition taken once from the Published state.
|
||||
let original_etag = agent_etag(&client, &base_url, &agent_id).await;
|
||||
let endpoint = format!("{base_url}/agents/{agent_id}/bindings");
|
||||
let payload_a = json!([binding(&operation_id, "edit_race_tool", "Race Winner A")]);
|
||||
let payload_b = json!([binding(&operation_id, "edit_race_tool", "Race Winner B")]);
|
||||
|
||||
let spawn_edit = |payload: Value, etag: String, endpoint: String| {
|
||||
let client = client.clone();
|
||||
tokio::spawn(async move {
|
||||
let response = client
|
||||
.post(endpoint)
|
||||
.header(reqwest::header::IF_MATCH, etag)
|
||||
.json(&payload)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let status = response.status();
|
||||
let body = response.json::<Value>().await.unwrap();
|
||||
(status, body)
|
||||
})
|
||||
};
|
||||
|
||||
let first = spawn_edit(payload_a, original_etag.clone(), endpoint.clone());
|
||||
let second = spawn_edit(payload_b, original_etag, endpoint);
|
||||
let (first, second) = tokio::join!(first, second);
|
||||
let results = vec![first.unwrap(), second.unwrap()];
|
||||
|
||||
let successes = results
|
||||
.iter()
|
||||
.filter(|(status, _)| status.is_success())
|
||||
.count();
|
||||
let conflicts = results
|
||||
.iter()
|
||||
.filter(|(status, _)| *status == reqwest::StatusCode::CONFLICT)
|
||||
.count();
|
||||
assert_eq!(
|
||||
successes, 1,
|
||||
"exactly one concurrent first edit must win: {results:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
conflicts, 1,
|
||||
"the losing concurrent first edit must report a stable conflict: {results:?}"
|
||||
);
|
||||
|
||||
let conflict_body = results
|
||||
.iter()
|
||||
.find(|(status, _)| *status == reqwest::StatusCode::CONFLICT)
|
||||
.map(|(_, body)| body)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
conflict_body["error"]["code"], "agent_stale_revision",
|
||||
"{conflict_body}"
|
||||
);
|
||||
|
||||
let summary = assert_success_json(
|
||||
client
|
||||
.get(format!("{base_url}/agents/{agent_id}"))
|
||||
.send()
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(summary["current_draft_version"], 2, "{summary}");
|
||||
assert_eq!(summary["latest_published_version"], 1, "{summary}");
|
||||
assert_eq!(
|
||||
agent_version_count(&db, &agent_id).await,
|
||||
2,
|
||||
"the losing concurrent edit must not fork a second Draft"
|
||||
);
|
||||
|
||||
let published_after = assert_success_json(
|
||||
client
|
||||
.get(format!("{base_url}/agents/{agent_id}/versions/1"))
|
||||
.send()
|
||||
.await
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(published_after, published_v1);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[serial]
|
||||
async fn first_edit_after_operation_archive_leaves_no_durable_draft() {
|
||||
let registry = test_registry().await;
|
||||
let db = registry.clone();
|
||||
let storage_root = test_storage_root("agent_catalog_edit_archive_ordering");
|
||||
let upstream_base_url = spawn_upstream_server().await;
|
||||
let base_url = spawn_admin_api(build_test_app(registry, storage_root)).await;
|
||||
let client = authorized_client(&base_url).await;
|
||||
|
||||
let live_operation =
|
||||
create_published_operation(&client, &base_url, &upstream_base_url, "edit_order_live").await;
|
||||
let (agent_id, published_v1) = create_published_agent(
|
||||
&client,
|
||||
&base_url,
|
||||
"edit-order",
|
||||
&live_operation,
|
||||
"edit_order_live",
|
||||
)
|
||||
.await;
|
||||
|
||||
let archived_operation = create_published_operation(
|
||||
&client,
|
||||
&base_url,
|
||||
&upstream_base_url,
|
||||
"edit_order_archived",
|
||||
)
|
||||
.await;
|
||||
let operation_etag = operation_etag(&client, &base_url, &archived_operation).await;
|
||||
let archived = client
|
||||
.post(format!(
|
||||
"{base_url}/operations/{archived_operation}/archive"
|
||||
))
|
||||
.header(reqwest::header::IF_MATCH, operation_etag)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let archived_status = archived.status();
|
||||
let archived_body = archived.text().await.unwrap();
|
||||
assert!(archived_status.is_success(), "{archived_body}");
|
||||
|
||||
let etag = agent_etag(&client, &base_url, &agent_id).await;
|
||||
let response = client
|
||||
.post(format!("{base_url}/agents/{agent_id}/bindings"))
|
||||
.header(reqwest::header::IF_MATCH, etag)
|
||||
.json(&json!([binding(
|
||||
&archived_operation,
|
||||
"edit_order_archived",
|
||||
"Archived Order Tool"
|
||||
)]))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let status = response.status();
|
||||
let body = response.text().await.unwrap();
|
||||
assert!(
|
||||
status.is_client_error(),
|
||||
"a first edit that references an archived Operation must be rejected: {status}: {body}"
|
||||
);
|
||||
|
||||
assert_no_durable_draft(&client, &db, &base_url, &agent_id, &published_v1).await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
#[serial]
|
||||
async fn first_edit_rejects_when_operation_archives_during_save() {
|
||||
let registry = test_registry().await;
|
||||
let db = registry.clone();
|
||||
let storage_root = test_storage_root("agent_catalog_edit_archive_race");
|
||||
let upstream_base_url = spawn_upstream_server().await;
|
||||
let base_url = spawn_admin_api(build_test_app(registry, storage_root)).await;
|
||||
let client = authorized_client(&base_url).await;
|
||||
|
||||
let live_operation =
|
||||
create_published_operation(&client, &base_url, &upstream_base_url, "edit_race_live").await;
|
||||
let (agent_id, published_v1) = create_published_agent(
|
||||
&client,
|
||||
&base_url,
|
||||
"edit-archive-race",
|
||||
&live_operation,
|
||||
"edit_race_live",
|
||||
)
|
||||
.await;
|
||||
|
||||
let target_operation =
|
||||
create_published_operation(&client, &base_url, &upstream_base_url, "edit_race_target")
|
||||
.await;
|
||||
|
||||
// Read the edit precondition before taking the Operation lock; Agent detail
|
||||
// may itself inspect bound Operations.
|
||||
let etag_response = client
|
||||
.get(format!("{base_url}/agents/{agent_id}"))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let etag_status = etag_response.status();
|
||||
let etag = etag_response
|
||||
.headers()
|
||||
.get(reqwest::header::ETAG)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.map(str::to_owned);
|
||||
let etag_body = etag_response.text().await.unwrap();
|
||||
assert_eq!(
|
||||
etag_status,
|
||||
reqwest::StatusCode::OK,
|
||||
"reading the Agent ETag before the archive race must succeed: {etag_body}"
|
||||
);
|
||||
let etag = etag.expect("Agent detail must expose an ETag");
|
||||
|
||||
// Use an independent pool for the holder and pg_stat_activity monitor. The
|
||||
// fixture registry has one connection, which the request needs to reach the
|
||||
// Operation lock wait.
|
||||
let lock_registry =
|
||||
PostgresRegistry::connect_with_options((*db.pool().connect_options()).clone())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Hold the target Operation row lock from a separate connection so the edit
|
||||
// transaction cannot complete its binding write until the archive wins.
|
||||
let mut holder = lock_registry.pool().begin().await.unwrap();
|
||||
sqlx::query("select id from operations where workspace_id = $1 and id = $2 for update")
|
||||
.bind(DEFAULT_WORKSPACE_ID)
|
||||
.bind(&target_operation)
|
||||
.fetch_one(&mut *holder)
|
||||
.await
|
||||
.unwrap();
|
||||
let holder_pid: i32 = sqlx::query_scalar("select pg_backend_pid()")
|
||||
.fetch_one(&mut *holder)
|
||||
.await
|
||||
.unwrap();
|
||||
let edit_client = client.clone();
|
||||
let endpoint = format!("{base_url}/agents/{agent_id}/bindings");
|
||||
let edit_target = target_operation.clone();
|
||||
let edit = tokio::spawn(async move {
|
||||
let response = edit_client
|
||||
.post(endpoint)
|
||||
.header(reqwest::header::IF_MATCH, etag)
|
||||
.json(&json!([binding(
|
||||
&edit_target,
|
||||
"edit_race_target",
|
||||
"Archive Race Tool"
|
||||
)]))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
let status = response.status();
|
||||
let body = response.text().await.unwrap();
|
||||
(status, body)
|
||||
});
|
||||
|
||||
// Wait for PostgreSQL to report the request blocked by this exact holder.
|
||||
// If the request completes first (the baseline CAS path), keep going so the
|
||||
// durable-draft assertion below reports that regression directly.
|
||||
let lock_wait = async {
|
||||
loop {
|
||||
if edit.is_finished() {
|
||||
return false;
|
||||
}
|
||||
let blocked: bool = sqlx::query_scalar(
|
||||
"select exists (
|
||||
select 1
|
||||
from pg_stat_activity
|
||||
where wait_event_type = 'Lock'
|
||||
and $1 = any(pg_blocking_pids(pid))
|
||||
and query ilike '%select status from operations%'
|
||||
)",
|
||||
)
|
||||
.bind(holder_pid)
|
||||
.fetch_one(lock_registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
if blocked {
|
||||
return true;
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
};
|
||||
let saw_operation_lock_wait =
|
||||
match tokio::time::timeout(std::time::Duration::from_secs(10), lock_wait).await {
|
||||
Ok(saw_wait) => saw_wait,
|
||||
Err(_) => {
|
||||
edit.abort();
|
||||
holder.rollback().await.unwrap();
|
||||
let _ = edit.await;
|
||||
panic!("timed out waiting for the edit to block on the held Operation row lock");
|
||||
}
|
||||
};
|
||||
|
||||
sqlx::query(
|
||||
"update operations
|
||||
set status = 'archived', updated_at = now()
|
||||
where workspace_id = $1 and id = $2",
|
||||
)
|
||||
.bind(DEFAULT_WORKSPACE_ID)
|
||||
.bind(&target_operation)
|
||||
.execute(&mut *holder)
|
||||
.await
|
||||
.unwrap();
|
||||
holder.commit().await.unwrap();
|
||||
|
||||
let (status, body) = edit.await.unwrap();
|
||||
assert!(
|
||||
status.is_client_error(),
|
||||
"an edit racing an Operation archive must be rejected: {status}: {body}"
|
||||
);
|
||||
|
||||
assert_no_durable_draft(&client, &db, &base_url, &agent_id, &published_v1).await;
|
||||
assert!(
|
||||
saw_operation_lock_wait,
|
||||
"a corrected save path must wait on the holder's Operation row lock before archive commits"
|
||||
);
|
||||
}
|
||||
@@ -48,3 +48,28 @@ fn admin_and_mcp_preserve_dispatch_uncertainty_without_changing_the_code() {
|
||||
assert!(!mcp.recoverable);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn admin_and_mcp_project_new_uncertain_upstream_codes_consistently() {
|
||||
for locale in [ExecutionLocale::En, ExecutionLocale::Ru] {
|
||||
for code in [
|
||||
ExecutionErrorCode::UpstreamRateLimited,
|
||||
ExecutionErrorCode::UpstreamServerError,
|
||||
ExecutionErrorCode::UpstreamResponseTooLarge,
|
||||
ExecutionErrorCode::UpstreamStatusError,
|
||||
] {
|
||||
let failure = ExecutionFailure::new(code, CorrelationContext::generate())
|
||||
.with_dispatch_uncertainty();
|
||||
let admin = execution_test_failure_localized(&failure, locale);
|
||||
let mcp = tool_error_contract_from_failure(&failure, locale);
|
||||
|
||||
assert_eq!(admin["code"], code.as_str());
|
||||
assert_eq!(admin["retryability"], "manual_reconcile");
|
||||
assert_eq!(admin["outcome_certainty"], "outcome_unknown");
|
||||
assert_eq!(admin["retryability"], mcp.retryability);
|
||||
assert_eq!(admin["outcome_certainty"], mcp.outcome_certainty);
|
||||
assert_eq!(mcp.error_code, code.as_str());
|
||||
assert!(!mcp.recoverable);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ FROM rust:1.96.1-bookworm AS deps
|
||||
WORKDIR /app
|
||||
|
||||
COPY Cargo.toml Cargo.lock ./
|
||||
COPY vendor ./vendor
|
||||
COPY .sqlx ./.sqlx
|
||||
COPY apps/admin-api/Cargo.toml apps/admin-api/Cargo.toml
|
||||
COPY apps/mcp-server/Cargo.toml apps/mcp-server/Cargo.toml
|
||||
@@ -41,6 +42,7 @@ FROM rust:1.96.1-bookworm AS builder
|
||||
WORKDIR /app
|
||||
|
||||
COPY Cargo.toml Cargo.lock ./
|
||||
COPY vendor ./vendor
|
||||
COPY .sqlx ./.sqlx
|
||||
COPY apps ./apps
|
||||
COPY crates ./crates
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
mod integration {
|
||||
mod catalog_access;
|
||||
mod common;
|
||||
mod execution_certainty;
|
||||
mod execution_stages;
|
||||
mod jsonrpc_correlation;
|
||||
mod request_context;
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
};
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::{Router, http::StatusCode, routing::post};
|
||||
use crank_core::{
|
||||
ExecutionErrorCode, InvocationSource, OutcomeCertainty, PlatformApiKeyScope, Retryability,
|
||||
WorkspaceId,
|
||||
};
|
||||
use crank_registry::{ListInvocationLogsQuery, PublishRequest};
|
||||
use serde_json::{Value, json};
|
||||
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
use super::common::{
|
||||
agent_mcp_url, build_test_app, create_platform_api_key, initialize_session,
|
||||
post_jsonrpc_response, publish_agent_for_operation, spawn_mcp_server, test_operation,
|
||||
test_registry, test_workspace_id,
|
||||
};
|
||||
|
||||
const REQUEST_ID: &str = "req_mcp_execution_certainty";
|
||||
|
||||
#[tokio::test]
|
||||
async fn ambiguous_post_failure_is_reported_and_persisted_as_unknown() {
|
||||
let registry = test_registry().await;
|
||||
let upstream_calls = Arc::new(AtomicUsize::new(0));
|
||||
let upstream_base_url = spawn_503_upstream(Arc::clone(&upstream_calls)).await;
|
||||
let operation = test_operation(&upstream_base_url, "mcp_execution_certainty");
|
||||
|
||||
registry
|
||||
.create_operation(&test_workspace_id(), &operation, Some("test"))
|
||||
.await
|
||||
.unwrap();
|
||||
registry
|
||||
.publish_operation(PublishRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
operation_id: &operation.id,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
|
||||
published_by: Some("test"),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
publish_agent_for_operation(®istry, &operation, "mcp-certainty-agent").await;
|
||||
let api_key = create_platform_api_key(
|
||||
®istry,
|
||||
"mcp-certainty-agent",
|
||||
"mcp-certainty-key",
|
||||
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
|
||||
)
|
||||
.await;
|
||||
let app = build_test_app(registry.clone(), Duration::ZERO, None);
|
||||
let base_url = spawn_mcp_server(app).await;
|
||||
let client = reqwest::Client::new();
|
||||
let mcp_url = agent_mcp_url(&base_url, "mcp-certainty-agent");
|
||||
let session_id = initialize_session(&client, &mcp_url, &api_key).await;
|
||||
|
||||
let response = post_jsonrpc_response(
|
||||
&client,
|
||||
&mcp_url,
|
||||
&api_key,
|
||||
Some(&session_id),
|
||||
Some(REQUEST_ID),
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 3,
|
||||
"method": "tools/call",
|
||||
"params": {
|
||||
"name": operation.name,
|
||||
"arguments": { "email": "user@example.com" }
|
||||
}
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let response: Value = response.json().await.unwrap();
|
||||
let tool_result = &response["result"];
|
||||
let error = &tool_result["structuredContent"]["error"];
|
||||
assert_eq!(tool_result["isError"], true);
|
||||
assert_eq!(error["code"], "upstream_server_error");
|
||||
assert_eq!(error["upstream_status"], 503);
|
||||
assert_eq!(error["retryability"], "manual_reconcile");
|
||||
assert_eq!(error["outcome_certainty"], "outcome_unknown");
|
||||
assert_eq!(error["recoverable"], false);
|
||||
assert_eq!(upstream_calls.load(Ordering::SeqCst), 1);
|
||||
|
||||
let logs = registry
|
||||
.list_invocation_logs(ListInvocationLogsQuery {
|
||||
workspace_id: &WorkspaceId::new("ws_default"),
|
||||
level: None,
|
||||
status: None,
|
||||
outcome_group: None,
|
||||
search_text: None,
|
||||
source: Some(InvocationSource::AgentToolCall),
|
||||
operation_id: Some(&operation.id),
|
||||
agent_id: None,
|
||||
created_after: None,
|
||||
created_before: None,
|
||||
cursor_created_at: None,
|
||||
cursor_id: None,
|
||||
limit: 10,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let invocation = logs
|
||||
.iter()
|
||||
.find(|record| record.log.request_id.as_deref() == Some(REQUEST_ID))
|
||||
.expect("Invocation History entry for this MCP request");
|
||||
assert_eq!(invocation.log.tool_name, operation.name);
|
||||
assert_eq!(invocation.log.operation_version, Some(1));
|
||||
assert_eq!(invocation.log.status_code, Some(503));
|
||||
assert_eq!(
|
||||
invocation.log.execution_error_code,
|
||||
Some(ExecutionErrorCode::UpstreamServerError)
|
||||
);
|
||||
assert_eq!(
|
||||
invocation.log.retryability,
|
||||
Some(Retryability::ManualReconcile)
|
||||
);
|
||||
assert_eq!(
|
||||
invocation.log.outcome_certainty,
|
||||
Some(OutcomeCertainty::OutcomeUnknown)
|
||||
);
|
||||
}
|
||||
|
||||
async fn spawn_503_upstream(calls: Arc<AtomicUsize>) -> String {
|
||||
let app = Router::new().route(
|
||||
"/crm/leads",
|
||||
post(move || {
|
||||
let calls = Arc::clone(&calls);
|
||||
async move {
|
||||
calls.fetch_add(1, Ordering::SeqCst);
|
||||
(StatusCode::SERVICE_UNAVAILABLE, "upstream unavailable")
|
||||
}
|
||||
}),
|
||||
);
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move {
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
});
|
||||
format!("http://{address}")
|
||||
}
|
||||
@@ -15,6 +15,10 @@ async function login(page) {
|
||||
await page.locator('.btn-signin').click();
|
||||
await expect(page).toHaveURL(/\/$/);
|
||||
await expect(page.locator('.page-title, .page-heading').first()).toBeVisible();
|
||||
await page.waitForFunction(() => Boolean(window.CrankAuth && typeof window.CrankAuth.fetchSession === 'function'));
|
||||
await page.evaluate(async () => {
|
||||
await window.CrankAuth.fetchSession(false);
|
||||
});
|
||||
}
|
||||
|
||||
async function browserJson(page, method, urlPath, body, okStatuses = [200]) {
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
const { test, expect } = require('@playwright/test');
|
||||
const { login } = require('./helpers');
|
||||
|
||||
test('login helper leaves a ready CSRF session under a delayed csrf refresh', async ({ page }) => {
|
||||
let csrfRequests = 0;
|
||||
await page.route('**/api/auth/session/csrf', async (route) => {
|
||||
csrfRequests += 1;
|
||||
await new Promise((resolve) => setTimeout(resolve, 800));
|
||||
await route.continue();
|
||||
});
|
||||
|
||||
await login(page);
|
||||
|
||||
const tokenReady = await page.evaluate(
|
||||
() => Boolean(window.CrankAuth && typeof window.CrankAuth.getCsrfToken === 'function' && window.CrankAuth.getCsrfToken())
|
||||
);
|
||||
expect(tokenReady).toBe(true);
|
||||
expect(csrfRequests).toBeGreaterThan(0);
|
||||
});
|
||||
@@ -156,7 +156,10 @@ test('onboarding error exposes safe support correlation and retries without a cl
|
||||
});
|
||||
|
||||
await page.goto('/');
|
||||
await page.getByTestId('onboarding-trigger').click();
|
||||
if (!await page.getByTestId('onboarding-checklist').isVisible()) {
|
||||
await page.getByTestId('onboarding-trigger').click();
|
||||
}
|
||||
await expect(page.getByTestId('onboarding-checklist')).toBeVisible();
|
||||
fail = true;
|
||||
await page.getByTestId('onboarding-refresh').click();
|
||||
const alert = page.getByRole('alert');
|
||||
@@ -198,7 +201,10 @@ test('validation, upstream and compatibility errors recover from the last author
|
||||
});
|
||||
|
||||
await page.goto('/');
|
||||
await page.getByTestId('onboarding-trigger').click();
|
||||
if (!await page.getByTestId('onboarding-checklist').isVisible()) {
|
||||
await page.getByTestId('onboarding-trigger').click();
|
||||
}
|
||||
await expect(page.getByTestId('onboarding-checklist')).toBeVisible();
|
||||
for (let index = 0; index < failures.length; index += 1) {
|
||||
failureIndex = index;
|
||||
await page.getByTestId('onboarding-refresh').click();
|
||||
|
||||
@@ -112,7 +112,7 @@ paths:
|
||||
await expect(importedOperation.locator('.openapi-import-mapping-preview')).toContainText('Header');
|
||||
await expect(importedOperation.locator('.openapi-import-mapping-preview')).toContainText('X-API-Version');
|
||||
await expect(importedOperation.locator('.openapi-import-mapping-preview')).toContainText('Body');
|
||||
await expect(importedOperation.locator('.openapi-import-mapping-preview')).toContainText('symbols');
|
||||
await expect(importedOperation.locator('.openapi-import-mapping-chip').filter({ hasText: /^body$/ })).toHaveCount(1);
|
||||
await expect(importedOperation.locator('.openapi-import-mapping-preview')).toContainText(localized('Response', 'Ответ'));
|
||||
await expect(page.locator('#openapi-import-selection')).toContainText(localized('Selected: 2', 'Выбрано: 2'));
|
||||
await page.locator('#openapi-import-search').fill('status');
|
||||
|
||||
@@ -500,11 +500,16 @@ impl ExecutionFailure {
|
||||
self.code,
|
||||
ExecutionErrorCode::UpstreamTimeout
|
||||
| ExecutionErrorCode::UpstreamTransportError
|
||||
| ExecutionErrorCode::UpstreamRateLimited
|
||||
| ExecutionErrorCode::UpstreamServerError
|
||||
| ExecutionErrorCode::UpstreamResponseTooLarge
|
||||
| ExecutionErrorCode::UpstreamStatusError
|
||||
| ExecutionErrorCode::IdempotencyOutcomeUnknown
|
||||
| ExecutionErrorCode::PersistenceUnavailable
|
||||
) {
|
||||
self.retryability = Retryability::ManualReconcile;
|
||||
self.outcome_certainty = OutcomeCertainty::OutcomeUnknown;
|
||||
self.retry_after_ms = None;
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
@@ -265,16 +265,111 @@ impl PostgresRegistry {
|
||||
&self,
|
||||
request: SaveAgentCatalogConfigRequest<'_>,
|
||||
) -> Result<(), RegistryError> {
|
||||
self.save_agent_catalog_config_inner(request, false)
|
||||
.await
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
pub async fn save_agent_catalog_config_editable(
|
||||
&self,
|
||||
request: SaveAgentCatalogConfigRequest<'_>,
|
||||
) -> Result<u32, RegistryError> {
|
||||
self.save_agent_catalog_config_inner(request, true).await
|
||||
}
|
||||
|
||||
async fn save_agent_catalog_config_inner(
|
||||
&self,
|
||||
request: SaveAgentCatalogConfigRequest<'_>,
|
||||
allow_fork: bool,
|
||||
) -> Result<u32, RegistryError> {
|
||||
let mut tx = self.pool.begin().await?;
|
||||
Self::lock_agent_and_validate_expected_state(
|
||||
let agent_row = Self::lock_agent_and_validate_expected_state(
|
||||
&mut tx,
|
||||
request.workspace_id,
|
||||
request.agent_id,
|
||||
request.expected_state,
|
||||
)
|
||||
.await?;
|
||||
Self::reject_published_agent_version(&mut tx, request.agent_id, request.agent_version)
|
||||
.await?;
|
||||
|
||||
if allow_fork {
|
||||
let status =
|
||||
deserialize_enum_text::<AgentStatus>(agent_row.try_get("status")?, "status")?;
|
||||
if status == AgentStatus::Archived {
|
||||
return Err(RegistryError::InvalidAgentTransition {
|
||||
agent_id: request.agent_id.as_str().to_owned(),
|
||||
from: "archived".to_owned(),
|
||||
action: "edit",
|
||||
});
|
||||
}
|
||||
let current_draft_version = from_db_version(
|
||||
agent_row.try_get("current_draft_version")?,
|
||||
"current_draft_version",
|
||||
)?;
|
||||
if request.agent_version != current_draft_version {
|
||||
return Err(RegistryError::InvalidAgentVersionSequence {
|
||||
agent_id: request.agent_id.as_str().to_owned(),
|
||||
expected: current_draft_version,
|
||||
actual: request.agent_version,
|
||||
});
|
||||
}
|
||||
let latest_published_version = agent_row
|
||||
.try_get::<Option<i32>, _>("latest_published_version")?
|
||||
.map(|value| from_db_version(value, "latest_published_version"))
|
||||
.transpose()?;
|
||||
|
||||
if latest_published_version == Some(current_draft_version) {
|
||||
let instructions = sqlx::query(
|
||||
"select instructions_json
|
||||
from agent_versions
|
||||
where agent_id = $1 and version = $2",
|
||||
)
|
||||
.bind(request.agent_id.as_str())
|
||||
.bind(to_db_version(current_draft_version))
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?
|
||||
.ok_or_else(|| RegistryError::AgentNotFound {
|
||||
agent_id: request.agent_id.as_str().to_owned(),
|
||||
})?
|
||||
.try_get::<Value, _>("instructions_json")?;
|
||||
|
||||
let now = time::OffsetDateTime::now_utc();
|
||||
let draft = AgentVersion {
|
||||
agent_id: request.agent_id.clone(),
|
||||
version: current_draft_version + 1,
|
||||
status: AgentStatus::Draft,
|
||||
instructions,
|
||||
tool_selection_policy: request.tool_selection_policy.clone(),
|
||||
created_at: now,
|
||||
};
|
||||
insert_agent_version_row(&mut tx, &draft).await?;
|
||||
replace_agent_bindings_rows(
|
||||
&mut tx,
|
||||
request.workspace_id,
|
||||
request.agent_id,
|
||||
draft.version,
|
||||
request.bindings,
|
||||
)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"update agents
|
||||
set current_draft_version = $3,
|
||||
updated_at = $4::timestamptz
|
||||
where workspace_id = $1 and id = $2",
|
||||
)
|
||||
.bind(request.workspace_id.as_str())
|
||||
.bind(request.agent_id.as_str())
|
||||
.bind(to_db_version(draft.version))
|
||||
.bind(now)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
return Ok(draft.version);
|
||||
}
|
||||
} else {
|
||||
Self::reject_published_agent_version(&mut tx, request.agent_id, request.agent_version)
|
||||
.await?;
|
||||
}
|
||||
|
||||
let updated = sqlx::query(
|
||||
"update agent_versions
|
||||
set tool_selection_policy_json = $3
|
||||
@@ -309,7 +404,7 @@ impl PostgresRegistry {
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await?;
|
||||
Ok(())
|
||||
Ok(request.agent_version)
|
||||
}
|
||||
|
||||
async fn lock_agent_and_validate_expected_state(
|
||||
@@ -317,7 +412,7 @@ impl PostgresRegistry {
|
||||
workspace_id: &WorkspaceId,
|
||||
agent_id: &AgentId,
|
||||
expected_state: Option<&AgentStateExpectation>,
|
||||
) -> Result<(), RegistryError> {
|
||||
) -> Result<sqlx::postgres::PgRow, RegistryError> {
|
||||
let row = sqlx::query(
|
||||
"select
|
||||
status,
|
||||
@@ -364,7 +459,7 @@ impl PostgresRegistry {
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
Ok(row)
|
||||
}
|
||||
|
||||
async fn reject_published_agent_version(
|
||||
|
||||
@@ -38,10 +38,13 @@ fn normalize_runtime_error_with_effect(
|
||||
) -> ExecutionFailure {
|
||||
let mut failure = ExecutionFailure::new(error_code(error), correlation.clone());
|
||||
match error {
|
||||
RuntimeError::ProtocolAdapter(ProtocolAdapterError::UnexpectedStatus {
|
||||
status, ..
|
||||
}) => {
|
||||
RuntimeError::ProtocolAdapter(
|
||||
adapter @ ProtocolAdapterError::UnexpectedStatus { status, .. },
|
||||
) => {
|
||||
failure = failure.with_upstream_status(*status);
|
||||
if may_mutate && ambiguous_after_dispatch(adapter) {
|
||||
failure = failure.with_dispatch_uncertainty();
|
||||
}
|
||||
}
|
||||
RuntimeError::ProtocolAdapter(adapter)
|
||||
if may_mutate && ambiguous_after_dispatch(adapter) =>
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crank_core::{
|
||||
CorrelationContext, DispatchEvidence, ExecutionErrorCode, ExecutionFailure, HttpMethod,
|
||||
OutcomeCertainty, Protocol, ProtocolAdapterError, RestTarget, Retryability, Target,
|
||||
ToolDescription,
|
||||
};
|
||||
use crank_mapping::MappingSet;
|
||||
use crank_runtime::{RuntimeError, RuntimeOperation, normalize_runtime_error_for_operation};
|
||||
use crank_schema::{Schema, SchemaKind};
|
||||
|
||||
const MUTATING_METHODS: [HttpMethod; 4] = [
|
||||
HttpMethod::Post,
|
||||
HttpMethod::Put,
|
||||
HttpMethod::Patch,
|
||||
HttpMethod::Delete,
|
||||
];
|
||||
const READ_METHODS: [HttpMethod; 2] = [HttpMethod::Get, HttpMethod::Head];
|
||||
const UNCERTAIN_STATUSES: [u16; 4] = [408, 429, 500, 503];
|
||||
|
||||
#[test]
|
||||
fn ambiguous_upstream_failures_are_unknown_only_for_dispatched_mutations() {
|
||||
let mut failures = Vec::new();
|
||||
for method in MUTATING_METHODS.into_iter().chain(READ_METHODS) {
|
||||
for dispatch in [
|
||||
DispatchEvidence::MayHaveDispatched,
|
||||
DispatchEvidence::NotDispatched,
|
||||
] {
|
||||
for status in UNCERTAIN_STATUSES {
|
||||
let error = RuntimeError::ProtocolAdapter(ProtocolAdapterError::UnexpectedStatus {
|
||||
status,
|
||||
dispatch,
|
||||
});
|
||||
if let Err(failure) = assert_normalization(
|
||||
method,
|
||||
&error,
|
||||
is_ambiguous_mutation(method, dispatch),
|
||||
Some(status),
|
||||
format!("{method:?} status {status} {dispatch:?}"),
|
||||
) {
|
||||
failures.push(failure);
|
||||
}
|
||||
}
|
||||
|
||||
for adapter in [
|
||||
ProtocolAdapterError::ResponseTooLarge { dispatch },
|
||||
ProtocolAdapterError::InvalidResponse { dispatch },
|
||||
] {
|
||||
let error = RuntimeError::ProtocolAdapter(adapter);
|
||||
if let Err(failure) = assert_normalization(
|
||||
method,
|
||||
&error,
|
||||
is_ambiguous_mutation(method, dispatch),
|
||||
None,
|
||||
format!("{method:?} {error:?}"),
|
||||
) {
|
||||
failures.push(failure);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
failures.is_empty(),
|
||||
"unexpected normalization rows:\n{}",
|
||||
failures.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nonambiguous_statuses_keep_their_existing_descriptor() {
|
||||
let mut failures = Vec::new();
|
||||
for method in MUTATING_METHODS.into_iter().chain(READ_METHODS) {
|
||||
for status in [401, 404] {
|
||||
let error = RuntimeError::ProtocolAdapter(ProtocolAdapterError::UnexpectedStatus {
|
||||
status,
|
||||
dispatch: DispatchEvidence::MayHaveDispatched,
|
||||
});
|
||||
if let Err(failure) = assert_normalization(
|
||||
method,
|
||||
&error,
|
||||
false,
|
||||
Some(status),
|
||||
format!("{method:?} nonambiguous status {status}"),
|
||||
) {
|
||||
failures.push(failure);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
failures.is_empty(),
|
||||
"unexpected normalization rows:\n{}",
|
||||
failures.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dispatch_uncertainty_allowlist_covers_uncertain_upstream_codes_and_drops_retry_delay() {
|
||||
let uncertain_codes = [
|
||||
ExecutionErrorCode::UpstreamRateLimited,
|
||||
ExecutionErrorCode::UpstreamServerError,
|
||||
ExecutionErrorCode::UpstreamResponseTooLarge,
|
||||
ExecutionErrorCode::UpstreamStatusError,
|
||||
];
|
||||
let mut failures = Vec::new();
|
||||
for code in uncertain_codes {
|
||||
let failure = ExecutionFailure::new(code, CorrelationContext::generate());
|
||||
let failure = if matches!(code.retryability(), Retryability::AfterDelay) {
|
||||
failure
|
||||
.try_with_retry_after_ms(1_000)
|
||||
.expect("retry delay is valid for the original descriptor")
|
||||
} else {
|
||||
failure
|
||||
}
|
||||
.with_dispatch_uncertainty();
|
||||
|
||||
if failure.error_code() != code
|
||||
|| failure.retryability() != Retryability::ManualReconcile
|
||||
|| failure.outcome_certainty() != OutcomeCertainty::OutcomeUnknown
|
||||
|| failure.retry_after_ms().is_some()
|
||||
{
|
||||
failures.push(format!(
|
||||
"{code:?}: actual code={:?}, retryability={:?}, certainty={:?}, retry_after_ms={:?}",
|
||||
failure.error_code(),
|
||||
failure.retryability(),
|
||||
failure.outcome_certainty(),
|
||||
failure.retry_after_ms(),
|
||||
));
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
failures.is_empty(),
|
||||
"uncertain code allowlist failures:\n{}",
|
||||
failures.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
fn assert_normalization(
|
||||
method: HttpMethod,
|
||||
error: &RuntimeError,
|
||||
unknown: bool,
|
||||
status: Option<u16>,
|
||||
context: String,
|
||||
) -> Result<(), String> {
|
||||
let correlation = CorrelationContext::generate();
|
||||
let failure = normalize_runtime_error_for_operation(error, &correlation, &operation(method));
|
||||
let code = expected_code(error);
|
||||
let expected = ExecutionFailure::new(code, correlation.clone());
|
||||
let expected_retryability = if unknown {
|
||||
Retryability::ManualReconcile
|
||||
} else {
|
||||
expected.retryability()
|
||||
};
|
||||
let expected_certainty = if unknown {
|
||||
OutcomeCertainty::OutcomeUnknown
|
||||
} else {
|
||||
expected.outcome_certainty()
|
||||
};
|
||||
|
||||
if failure.error_code() != code
|
||||
|| failure.retryability() != expected_retryability
|
||||
|| failure.outcome_certainty() != expected_certainty
|
||||
|| failure.upstream_status() != status
|
||||
|| failure.retry_after_ms().is_some()
|
||||
{
|
||||
return Err(format!(
|
||||
"{context}: code={:?} (expected {code:?}), retryability={:?} (expected {expected_retryability:?}), certainty={:?} (expected {expected_certainty:?}), upstream_status={:?} (expected {status:?}), retry_after_ms={:?}",
|
||||
failure.error_code(),
|
||||
failure.retryability(),
|
||||
failure.outcome_certainty(),
|
||||
failure.upstream_status(),
|
||||
failure.retry_after_ms(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn expected_code(error: &RuntimeError) -> ExecutionErrorCode {
|
||||
match error {
|
||||
RuntimeError::ProtocolAdapter(ProtocolAdapterError::UnexpectedStatus {
|
||||
status, ..
|
||||
}) => match status {
|
||||
401 | 403 => ExecutionErrorCode::UpstreamAuthError,
|
||||
404 => ExecutionErrorCode::UpstreamNotFound,
|
||||
408 | 429 => ExecutionErrorCode::UpstreamRateLimited,
|
||||
500..=599 => ExecutionErrorCode::UpstreamServerError,
|
||||
_ => ExecutionErrorCode::UpstreamStatusError,
|
||||
},
|
||||
RuntimeError::ProtocolAdapter(ProtocolAdapterError::ResponseTooLarge { .. }) => {
|
||||
ExecutionErrorCode::UpstreamResponseTooLarge
|
||||
}
|
||||
RuntimeError::ProtocolAdapter(ProtocolAdapterError::InvalidResponse { .. }) => {
|
||||
ExecutionErrorCode::UpstreamStatusError
|
||||
}
|
||||
other => panic!("unexpected test fixture: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_ambiguous_mutation(method: HttpMethod, dispatch: DispatchEvidence) -> bool {
|
||||
MUTATING_METHODS.contains(&method) && dispatch == DispatchEvidence::MayHaveDispatched
|
||||
}
|
||||
|
||||
fn operation(method: HttpMethod) -> RuntimeOperation {
|
||||
RuntimeOperation {
|
||||
operation_id: crank_core::OperationId::new("certainty_test"),
|
||||
operation_version: 1,
|
||||
tool_name: "certainty_test".to_owned(),
|
||||
protocol: Protocol::Rest,
|
||||
target: Target::Rest(RestTarget {
|
||||
base_url: "https://example.invalid".to_owned(),
|
||||
method,
|
||||
path_template: "/items".to_owned(),
|
||||
static_headers: BTreeMap::new(),
|
||||
request_contract: None,
|
||||
response_contract: Vec::new(),
|
||||
multipart_field_mime_types: BTreeMap::new(),
|
||||
}),
|
||||
input_schema: empty_schema(),
|
||||
output_schema: empty_schema(),
|
||||
input_mapping: MappingSet::default(),
|
||||
output_mapping: MappingSet::default(),
|
||||
execution_config: crank_core::ExecutionConfig::default(),
|
||||
tool_description: ToolDescription {
|
||||
title: "Certainty test".to_owned(),
|
||||
description: "Execution certainty fixture".to_owned(),
|
||||
tags: Vec::new(),
|
||||
examples: Vec::new(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn empty_schema() -> Schema {
|
||||
Schema {
|
||||
kind: SchemaKind::Object,
|
||||
format: None,
|
||||
description: None,
|
||||
required: true,
|
||||
nullable: false,
|
||||
default_value: None,
|
||||
fields: BTreeMap::new(),
|
||||
items: None,
|
||||
enum_values: Vec::new(),
|
||||
variants: Vec::new(),
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,10 @@ Crank превращает REST API endpoint-ы в MCP-инструменты,
|
||||
- [Capability Baseline](./capability-baseline/manifest.json) — versioned SHA-256
|
||||
snapshot фактических UI, Admin API и MCP flows, taxonomy, checklist и
|
||||
sanitized evidence results.
|
||||
- [Evidence разработки](./development-evidence.md) — clean baseline, проверенная
|
||||
revision реализации и отдельная запись текущего completion evidence.
|
||||
- [Completion evidence Epic 1](./epic-1-completion/index.json) — актуальные
|
||||
development checks после исправлений ретроспективы.
|
||||
- [Schema Capability Baseline](./schemas/capability-baseline.schema.json) —
|
||||
fail-closed manifest contract.
|
||||
- [Настройки окружения](./runtime-config.md)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,268 @@
|
||||
# SQLx-core 0.9.0: bounded maintenance и упорядочивание публикации idle
|
||||
|
||||
Этот документ описывает единственный отслеживаемый патч стороннего крейта в
|
||||
репозитории: `sqlx-core` 0.9.0. Относительно архива crates.io меняется только
|
||||
код `src/pool/inner.rs` (два private seam, детерминированные regression-тесты и
|
||||
modification notice); дополнительно два файла лицензий восстановлены полным
|
||||
текстом с закреплённого upstream-тега. Публичный API, feature-набор, таймауты и
|
||||
семантика пула не меняются.
|
||||
|
||||
## Provenance
|
||||
|
||||
- Package: `sqlx-core` версии `0.9.0`.
|
||||
- Лицензия в манифесте: `MIT OR Apache-2.0`.
|
||||
- Источник vendoring: `index.crates.io-1949cf8c6b5b557f/sqlx-core-0.9.0.crate`.
|
||||
- SHA-256 архива: `05b44e85bf579a8eeb4ceaa77a3a523baf2bf0e9bac7e40f405d537b5d2d5ccb`.
|
||||
Совпадает с checksum в исходном `Cargo.lock` до патча.
|
||||
- Размещение: `vendor/sqlx-core/` (безопасное извлечение архива целиком).
|
||||
- `LICENSE-MIT` и `LICENSE-APACHE` в опубликованном крейте — текстовые заглушки
|
||||
`../LICENSE-MIT` / `../LICENSE-APACHE`. При vendoring они восстановлены полным
|
||||
оригинальным текстом с закреплённого upstream-тега (см. «Лицензии» ниже).
|
||||
- Метаданные registry-кэша (`.cargo-checksum.json`) не добавлялись.
|
||||
- Нормализованный upstream-манифест `vendor/sqlx-core/Cargo.toml` не
|
||||
переписывался; version, features и зависимости не менялись.
|
||||
|
||||
### Подключение
|
||||
|
||||
В корневом `Cargo.toml`:
|
||||
|
||||
```toml
|
||||
[workspace]
|
||||
exclude = ["vendor/sqlx-core"]
|
||||
|
||||
[patch.crates-io]
|
||||
sqlx-core = { path = "vendor/sqlx-core" }
|
||||
```
|
||||
|
||||
В `Cargo.lock` запись `sqlx-core` перестаёт быть registry-пакетом: удаляются
|
||||
строки `source = "registry+..."` и `checksum = "..."`, пакет становится path.
|
||||
Других изменений в `Cargo.lock` нет.
|
||||
|
||||
### Изменённые относительно архива файлы
|
||||
|
||||
`diff -rq` против распакованного архива `sqlx-core-0.9.0.crate` даёт ровно три
|
||||
отличия:
|
||||
|
||||
- `src/pool/inner.rs` — единственный изменённый **код** (seams, regression-тесты,
|
||||
modification notice);
|
||||
- `LICENSE-MIT` и `LICENSE-APACHE` — восстановлены из upstream-тега.
|
||||
|
||||
Остальные файлы архива (включая `Cargo.toml`, `Cargo.toml.orig`, `Cargo.lock`,
|
||||
`.cargo_vcs_info.json` и весь остальной `src/`) побайтово не менялись.
|
||||
|
||||
### Лицензии
|
||||
|
||||
Полные тексты взяты из закреплённого upstream-тега `v0.9.0`:
|
||||
|
||||
- `LICENSE-MIT` — <https://raw.githubusercontent.com/transact-rs/sqlx/v0.9.0/LICENSE-MIT>,
|
||||
SHA-256 `5abbdd842310c8f1650fcde3a5a51a3e09412b9e5a6eea87519e0db9e32b339d`;
|
||||
- `LICENSE-APACHE` — <https://raw.githubusercontent.com/transact-rs/sqlx/v0.9.0/LICENSE-APACHE>,
|
||||
SHA-256 `c8f5453612253e8ea8bad241617fe74c4a6d5d592ba64ff881668c211b50ac99`.
|
||||
|
||||
Копирайт- и лицензионные уведомления upstream не удалялись и не переписывались.
|
||||
|
||||
## Наблюдавшийся дефект
|
||||
|
||||
При повторном полном gate на ревизии `1b9f7f66f9f89dcfed8d4d2efa71986063741ca0`
|
||||
существовавший integration-тест `community_access_usage` повторно уходил в
|
||||
sustained Tokio CPU busy loop. Собрано 100 userspace instruction-pointer
|
||||
samples; среди них присутствуют:
|
||||
|
||||
- `sqlx_core::pool::inner::spawn_maintenance_tasks::{{closure}}::{{closure}}`
|
||||
на `src/pool/inner.rs:549`;
|
||||
- `PoolInner<DB>::try_acquire` (`inner.rs:182`) и `PoolInner<DB>::release`;
|
||||
- `crossbeam_queue::array_queue::ArrayQueue::pop`,
|
||||
`core::sync::atomic::Atomic<usize>::fetch_sub/fetch_add`.
|
||||
|
||||
Важная оговорка: **live-значения `num_idle`/`MAX` не снимались**. Захват
|
||||
samples показывает hotspot, но не доказывает, что в проде наблюдался именно
|
||||
`usize::MAX`. Считаем наблюдаемым только сам hot loop; MAX-сценарий
|
||||
демонстрируется отдельно, принудительным interleaving в unit-тесте.
|
||||
|
||||
### Достижимая гонка в исходнике
|
||||
|
||||
В upstream `release()` соединение публикуется в `idle_conns`, затем
|
||||
отпускается permit, и только потом увеличивается `num_idle`:
|
||||
|
||||
```rust
|
||||
if self.idle_conns.push(idle).is_err() { /* panic */ }
|
||||
guard.release_permit();
|
||||
self.num_idle.fetch_add(1, Ordering::AcqRel);
|
||||
```
|
||||
|
||||
Параллельный `try_acquire()` может выполнить `pop_idle()` в окне между
|
||||
`push`/`release_permit` и `fetch_add`. Тогда `num_idle.fetch_sub(1)` при
|
||||
исходном нуле временно уходит в underflow (`0 - 1` → `usize::MAX`), а
|
||||
последующий `fetch_add(1)` возвращает счётчик к нулю. В этом окне maintenance
|
||||
task читает `num_idle` и выполняет `for _ in 0..pool.num_idle()` — без
|
||||
ограничения сверху, то есть потенциально огромный диапазон.
|
||||
|
||||
## Патч
|
||||
|
||||
Полные unified diff лежат в evidence рядом с completion-отчётом:
|
||||
[`docs/epic-1-completion/evidence/sqlx-red.patch`](../epic-1-completion/evidence/sqlx-red.patch)
|
||||
(исходное RED-состояние) и
|
||||
[`docs/epic-1-completion/evidence/sqlx-accepted.patch`](../epic-1-completion/evidence/sqlx-accepted.patch)
|
||||
(принятая версия). SHA-256 патчей зафиксированы в metadata. Ниже — суть
|
||||
принятого изменения.
|
||||
|
||||
### 1. Bounded maintenance batch
|
||||
|
||||
Новый private helper, используемый реальным for-loop в
|
||||
`spawn_maintenance_tasks`:
|
||||
|
||||
```rust
|
||||
fn maintenance_batch_size(num_idle: usize, capacity: usize) -> usize {
|
||||
cmp::min(num_idle, capacity)
|
||||
}
|
||||
```
|
||||
|
||||
```rust
|
||||
let batch_size = maintenance_batch_size(
|
||||
pool.num_idle(),
|
||||
pool.options.max_connections as usize,
|
||||
);
|
||||
for _ in 0..batch_size {
|
||||
if let Some(conn) = pool.try_acquire() { /* ... */ }
|
||||
}
|
||||
```
|
||||
|
||||
`num_idle` не может легитимно превышать capacity; ограничение не отключает
|
||||
maintenance и не меняет период/таймауты.
|
||||
|
||||
### 2. Резервирование idle-счётчика до публикации
|
||||
|
||||
`release()` теперь публикует через helper, который увеличивает `num_idle` до
|
||||
вызова публикующего callback и откатывает изменение при ошибке:
|
||||
|
||||
```rust
|
||||
fn publish_idle_connection<F, E>(num_idle: &AtomicUsize, publish: F) -> Result<(), E>
|
||||
where
|
||||
F: FnOnce() -> Result<(), E>,
|
||||
{
|
||||
num_idle.fetch_add(1, Ordering::AcqRel);
|
||||
|
||||
if let Err(error) = publish() {
|
||||
num_idle.fetch_sub(1, Ordering::AcqRel);
|
||||
return Err(error);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
Callback естественно возвращает ошибку push как `Result<(), Idle<DB>>`:
|
||||
|
||||
```rust
|
||||
let published = publish_idle_connection(&self.num_idle, move || {
|
||||
// NOTE: permit отпускается только после удачного push
|
||||
self.idle_conns
|
||||
.push(idle)
|
||||
.map(|()| guard.release_permit())
|
||||
});
|
||||
|
||||
if published.is_err() {
|
||||
panic!("BUG: connection queue overflow in release()");
|
||||
}
|
||||
```
|
||||
|
||||
`guard.release_permit()` вызывается только при удачном push, то есть порядок
|
||||
push-before-release-permit сохранён. Существующий
|
||||
`panic!("BUG: connection queue overflow in release()")` сохранён, но вынесен
|
||||
**наружу** `publish_idle_connection` и срабатывает уже после отката резерва.
|
||||
Поэтому ветка отката — реальный production-путь (переполнение очереди), а не
|
||||
защитная недостижимая ветка.
|
||||
|
||||
Важно: `maintenance_batch_size` ограничивает только объём maintenance-скана по
|
||||
capacity. Это **не** защита от переполнения `idle_conns` — это разные инварианты,
|
||||
и один не подменяет другой.
|
||||
|
||||
### Регрессионные тесты
|
||||
|
||||
Тесты используют фактический private helper, применяемый в `release()`, а не
|
||||
проверку текста исходника:
|
||||
|
||||
- `maintenance_batch_size_bounds_scan_by_capacity` — оракул для `0`, `1`,
|
||||
`capacity`, `capacity + 1`, `usize::MAX`; ожидается ограничение capacity при
|
||||
сохранении нормальных значений. MAX проверяется без запуска цикла на
|
||||
`usize::MAX`.
|
||||
- `publish_reserves_idle_counter_before_connection_is_visible` — детерминированная
|
||||
модель гонки: `ArrayQueue` + `AtomicUsize` + две фазы `Barrier` в двух
|
||||
потоках. Producer публикует соединение, затем сигналит consumer и ждёт его
|
||||
`pop` до возврата из callback. Consumer записывает *предыдущее* значение
|
||||
`fetch_sub` и не утверждает его до второго barrier/join, чтобы RED не
|
||||
превратился в deadlock. Ожидается `previous == 1` и финальный счётчик `0`.
|
||||
В исходном порядке наблюдается `previous == 0` (даже если поздний
|
||||
wrapping-`fetch_add` возвращает `0`).
|
||||
- `publish_rolls_back_idle_counter_when_publication_fails` — при `Err` из
|
||||
callback счётчик не должен «утечь». Production `release()` возвращает именно
|
||||
ошибку push (`Idle<DB>`); тест использует строковую ошибку, чтобы проверить
|
||||
тот же контракт helper без конструирования подключения к БД.
|
||||
|
||||
Никаких test-only sleep, mock DB, файлов или сети; все утверждения
|
||||
детерминированы и ограничены.
|
||||
|
||||
## Evidence
|
||||
|
||||
Команда запускалась напрямую по манифесту vendored-крейта как самостоятельного
|
||||
пакета:
|
||||
|
||||
```text
|
||||
cargo test --manifest-path vendor/sqlx-core/Cargo.toml --locked --lib
|
||||
```
|
||||
|
||||
Запуск использовал изолированные `CARGO_HOME` и `CARGO_TARGET_DIR`, поэтому
|
||||
отслеживаемый `Cargo.lock` крейта и глобальный cargo cache не изменялись;
|
||||
конкретные пути машины здесь не приводятся.
|
||||
|
||||
RED (`sqlx-red.log`, exit `101`):
|
||||
|
||||
```text
|
||||
test pool::inner::tests::maintenance_batch_size_bounds_scan_by_capacity ... FAILED
|
||||
test pool::inner::tests::publish_reserves_idle_counter_before_connection_is_visible ... FAILED
|
||||
test pool::inner::tests::publish_rolls_back_idle_counter_when_publication_fails ... ok
|
||||
test result: FAILED. 1 passed; 2 failed; 0 ignored; 0 measured; 2 filtered out
|
||||
```
|
||||
|
||||
Падения RED: `left: 9, right: 8` (не ограничено capacity) и
|
||||
`idle counter must be reserved before the connection is visible, saw 0`
|
||||
(подтверждён `previous == 0`). Deadlock не возник, потому что проверка
|
||||
отложена до join.
|
||||
|
||||
GREEN (`sqlx-green.log`, exit `0`):
|
||||
|
||||
```text
|
||||
test io::read_buf::test_read_buf_bytes_mut ... ok
|
||||
test pool::assert_pool_traits ... ok
|
||||
test pool::inner::tests::maintenance_batch_size_bounds_scan_by_capacity ... ok
|
||||
test pool::inner::tests::publish_reserves_idle_counter_before_connection_is_visible ... ok
|
||||
test pool::inner::tests::publish_rolls_back_idle_counter_when_publication_fails ... ok
|
||||
test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
|
||||
```
|
||||
|
||||
Существующие upstream-тесты (`pool::assert_pool_traits`,
|
||||
`io::read_buf::test_read_buf_bytes_mut`) не отключены и проходят.
|
||||
|
||||
Принятая версия (после follow-up правок: natural `Result<(), Idle<DB>>` с
|
||||
panic снаружи helper, восстановленные лицензии, modification notice) повторно
|
||||
прогнана тем же `cargo test --manifest-path vendor/sqlx-core/Cargo.toml --locked --lib`
|
||||
с результатом `5 passed; 0 failed` (полный лог — `sqlx-accepted.log`).
|
||||
|
||||
Дополнительно на принятой версии:
|
||||
|
||||
- `cargo check -p crank-registry -p admin-api` (`SQLX_OFFLINE=true`, `--offline`) — успешно;
|
||||
- `cargo deny --locked check advisories bans licenses sources` —
|
||||
`advisories ok, bans ok, licenses ok, sources ok`;
|
||||
- `rustfmt --edition 2021 --check vendor/sqlx-core/src/pool/inner.rs` — чисто.
|
||||
|
||||
## Ограничения и maintenance burden
|
||||
|
||||
- Unit-тесты моделируют достижимое interleaving, но **не доказывают, что в
|
||||
production наблюдался `usize::MAX`**. Наблюдаемым фактом остаются hot loop и
|
||||
цепочка maintenance/try_acquire/release по samples.
|
||||
- Это отслеживаемый source patch сторонней зависимости. Он требует ручного
|
||||
переприменения/rebase при обновлении `sqlx-core` и должен быть удалён, как
|
||||
только подтверждённый upstream-fix войдёт в используемую версию.
|
||||
- Публичный API, схемы, feature-набор и таймауты не менялись; maintenance не
|
||||
отключался.
|
||||
- Тесты не отключались; глобальный cargo cache не редактировался.
|
||||
@@ -0,0 +1,89 @@
|
||||
# Evidence разработки
|
||||
|
||||
Этот порядок помогает восстановить состояние кода и результат каждого
|
||||
проверяемого этапа. Он не заменяет [Capability Baseline](./capability-baseline/manifest.json):
|
||||
baseline хранит версионированный снимок capability Inventory и исторические
|
||||
результаты, а completion evidence указывает, что именно проверено для текущего
|
||||
этапа или завершения.
|
||||
|
||||
## Ревизии этапа
|
||||
|
||||
До начала этапа запишите полный Git commit `baseline_commit` и убедитесь, что
|
||||
`git status --short` пуст. Это проверка tracked, staged и обычных untracked
|
||||
изменений; игнорируемые локальные файлы не входят в Git baseline. Не записывайте
|
||||
`baseline + uncommitted worktree` как revision.
|
||||
|
||||
После изменений сохраните проверенный implementation revision отдельным полным
|
||||
commit hash. Проверки, которые подтверждают завершение этапа, должны относиться
|
||||
к этому commit при чистом worktree. Укажите использованные конфигурацию и
|
||||
класс окружения: одинаковый commit сам по себе не описывает их.
|
||||
|
||||
Если нужен RED до коммита, зафиксируйте его как промежуточное наблюдение: укажите
|
||||
`baseline_commit`, SHA-256 сохранённого diff/artifact, включающего изменения
|
||||
(в том числе untracked test files), команду и её фактический результат. Не
|
||||
представляйте baseline вместе с незакоммиченным diff как implementation revision.
|
||||
После RED повторите нужные проверки на отдельном чистом implementation revision.
|
||||
|
||||
## Запись completion evidence
|
||||
|
||||
Для текущего завершения используйте отдельный versioned index и sanitized
|
||||
evidence-файлы с устойчивыми repository-relative ссылками. Запись должна позволять
|
||||
повторно определить проверенное состояние и результат, не сохраняя секреты,
|
||||
локальные абсолютные пути или произвольные payloads. Для каждой проверки укажите:
|
||||
|
||||
- идентификатор этапа/запуска и полный `baseline_commit`;
|
||||
- полный `implementation_revision` проверенного commit;
|
||||
- конфигурацию/toolchain и класс окружения;
|
||||
- точную команду, exit code и фактические counts `passed`, `failed`, `skipped`
|
||||
(или эквивалентный summary для команды без тестового счётчика);
|
||||
- repository-relative путь к sanitised log/report и его SHA-256.
|
||||
|
||||
Если результаты не относятся к одной и той же ревизии, конфигурации или
|
||||
окружению, записывайте их раздельно. Не выводите PASS из exit code без проверки
|
||||
счётчиков и пропусков; сохраняйте fail, flaky, skipped, not-run и manual-only
|
||||
как наблюдались. Новое completion evidence не переписывает historical baseline
|
||||
или его manual failures.
|
||||
|
||||
Изменение canonical Capability Inventory status/evidence по-прежнему требует
|
||||
обновить versioned `docs/capability-baseline/manifest.json`, sanitized
|
||||
`docs/capability-baseline/results.json`, `baseline_version` и SHA-256 согласно
|
||||
его schema и проверкам. Отдельный completion index не ослабляет и не обходит
|
||||
этот gate.
|
||||
|
||||
Компактный шаблон записи:
|
||||
|
||||
```yaml
|
||||
id: <stage-or-run-id>
|
||||
baseline_commit: <full-git-commit>
|
||||
implementation_revision: <full-git-commit>
|
||||
environment:
|
||||
class: <environment-class>
|
||||
config: <tracked-config-or-versioned-reference>
|
||||
command: <exact-command>
|
||||
exit_code: <actual-integer>
|
||||
counts:
|
||||
passed: <actual-count>
|
||||
failed: <actual-count>
|
||||
skipped: <actual-count>
|
||||
evidence:
|
||||
path: <repository-relative-sanitized-report>
|
||||
sha256: <sha256-of-report>
|
||||
```
|
||||
|
||||
Для промежуточного RED вместо `implementation_revision` укажите
|
||||
`diff_sha256` и ссылку на сохранённый diff/artifact; не выдавайте его за
|
||||
проверенный implementation commit.
|
||||
|
||||
## Условия воспроизводимого запуска
|
||||
|
||||
Сохраняйте рабочие журналы за пределами временного каталога ОС и переносите
|
||||
обезличенные summaries и digests в versioned evidence при завершении этапа.
|
||||
Перезапуск окружения может удалить временные журналы; потерянный первичный лог
|
||||
нельзя заменять утверждением, что проверка прошла.
|
||||
|
||||
Для разных checkout задавайте разные `CARGO_TARGET_DIR`: сборка baseline
|
||||
с общим target может подменить артефакт проверяемой реализации. Полный
|
||||
`just verify` запускайте отдельно от UI stack: startup tests используют
|
||||
стандартные metrics ports. Для capture используйте pipe и запись родителем:
|
||||
прямое перенаправление в обычный файл влияет на дочерние tests с `RLIMIT_FSIZE`.
|
||||
Прерванный запуск сохраняйте отдельно от последующего успешного.
|
||||
@@ -0,0 +1,77 @@
|
||||
# Completion evidence Epic 1
|
||||
|
||||
Этот каталог хранит проверки разработки Epic 1 после исправлений ретроспективы.
|
||||
Ревизии, команды, результаты и SHA-256 обезличенных отчётов перечислены в
|
||||
[index.json](./index.json). Итоговый статус читается из индекса.
|
||||
|
||||
[Capability Baseline](../capability-baseline/results.json) версии `2026.08.24.1`
|
||||
проверял `767428436d3a54e60809a727044dfcec48e1f1dd`, до завершения Story 1.7–1.16.
|
||||
Его результаты остаются историческим снимком: manual failures `UI-02`, `UI-04`,
|
||||
`UI-05`, `UI-07`–`UI-12` и старые `DEF-BL-*`/`DEF-UI-*` этим отчётом не
|
||||
переписываются. Новые автоматизированные проверки не означают повторную ручную
|
||||
приёмку каждого прежнего сценария.
|
||||
|
||||
Проверки относятся к development acceptance. Внешние human usability (`UI-13`),
|
||||
Reference и длительные qualification остаются `not_run` по
|
||||
[acceptance plan](../acceptance-test-plan.md). Наличие плана не считается PASS.
|
||||
|
||||
Для повторения используйте точный implementation commit из записи запуска и
|
||||
его конфигурацию/toolchain. RED указан отдельно как baseline вместе с сохранённым
|
||||
тестовым diff; это не чистая implementation revision. Порядок записи описан в
|
||||
[development evidence](../development-evidence.md).
|
||||
|
||||
`just verify` выполняется отдельно от UI stack: startup tests используют
|
||||
стандартный metrics bind, занятый работающим stack. Вывод записывался через pipe: родительский процесс сохранял лог.
|
||||
Прямое перенаправление stdout в обычный файл меняет условия дочернего теста
|
||||
`RLIMIT_FSIZE=1`, ограничивая и test reporter. Для разных checkout используйте
|
||||
разные `CARGO_TARGET_DIR`, чтобы baseline build не подменил артефакты реализации.
|
||||
|
||||
Browser probe требует stack, поднятый `bash apps/ui/scripts/playwright-stack.sh`
|
||||
с настройками по умолчанию. После его готовности запустите
|
||||
`node docs/epic-1-completion/evidence/agent-probe.cjs`; после проверки остановите
|
||||
stack через Ctrl-C. Probe создаёт synthetic Agent, публикует v1, выполняет первый
|
||||
post-publish edit и проверяет сохранность Published snapshot.
|
||||
|
||||
Наблюдения предыдущего запуска, чьи `/tmp`-журналы исчезли после перезапуска
|
||||
окружения, перечислены как ограничения; они не используются вместо свежих
|
||||
сохранённых проверок. Для SQLx maintenance принят локальный patch:
|
||||
ограничен размер batch, счётчик idle резервируется до публикации в очередь.
|
||||
Forced-interleaving RED/GREEN подтверждает гонку исходного порядка операций;
|
||||
значение MAX в зависшем процессе не измерялось. Patch нужно сопровождать до
|
||||
проверенного upstream исправления; provenance описан в
|
||||
[dependency patch](../dependency-patches/sqlx-core-0.9.0.md).
|
||||
|
||||
Полный Rust/tooling gate и финальный UI прогон имеют отдельные source revisions.
|
||||
Между ними изменён только onboarding E2E test: вместо безусловного toggle
|
||||
он проверяет видимость автоматически открываемой панели. Exact changed paths
|
||||
записаны в `workspace_source_equivalence`; Rust source/tests/scripts/Cargo
|
||||
конфигурация полностью совпадают. Наблюдённый flaky UI запуск сохранён отдельно;
|
||||
финальные UI проверки выполняются с `--retries=0`.
|
||||
|
||||
|
||||
## Перенос исправлений в PR #83
|
||||
|
||||
[Отдельный отчёт переноса](./pr-integration-2026-10-05.json) и его сохранённые
|
||||
журналы фиксируют свежие проверки изолированной ветки на серверной `main`.
|
||||
Исторический `index.json` выше относится к прежней локальной ветке; исходные
|
||||
коммиты перенесены через cherry-pick и имеют другие идентификаторы в PR.
|
||||
Это отдельные наборы результатов. Между свежим Rust gate и браузерными
|
||||
проверками изменены только инструкции копирования `vendor` в Dockerfile;
|
||||
точные ревизии и пути сохранены в новом отчёте. Последующее добавление этих
|
||||
журналов и плана приёмки меняет только документацию.
|
||||
|
||||
План приёмки включён в репозиторий для разрешения ссылки из исторического
|
||||
отчёта. Он описывает будущие проверки всех эпиков и не означает их выполнения.
|
||||
Внешняя человеческая приёмка и длительные испытания сохраняют статус `not_run`.
|
||||
Серверные проверки сборки и тестов доступны в [PR #83](https://git.itexp.me/bsodfather/crank/pulls/83).
|
||||
|
||||
|
||||
### Полный браузерный набор после проверки CI
|
||||
|
||||
[Актуальная проверка браузерного набора](./pr-browser-reconciliation-2026-10-05.json)
|
||||
сохраняет 57 успешных сценариев без повторов, включая постоянный тест готовности
|
||||
сессии при задержанной выдаче CSRF. После исходного отчёта переноса изменены
|
||||
только тестовый помощник входа и два существующих сценария, добавлен один
|
||||
регрессионный тест. Производственный код не менялся. Отчёт содержит SHA каждого
|
||||
тестового файла и журналы воспроизведения до исправления, включая промежуточный
|
||||
отказ CSRF; предыдущие результаты не переписываются.
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"before_draft": 1,
|
||||
"after_draft": 2,
|
||||
"saved_version": 2,
|
||||
"published_unchanged": true,
|
||||
"error": null
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
const assert = require('node:assert/strict');
|
||||
const { chromium } = require(process.env.CRANK_PROBE_PLAYWRIGHT || require('node:path').resolve(__dirname, '../../../apps/ui/node_modules/@playwright/test'));
|
||||
(async () => {
|
||||
const browser = await chromium.launch();
|
||||
try {
|
||||
const page = await browser.newPage();
|
||||
await page.goto('http://127.0.0.1:3300/login');
|
||||
await page.locator('#email').fill('owner@crank.local');
|
||||
await page.locator('#password').fill('change-me-admin-password');
|
||||
await page.locator('.btn-signin').click();
|
||||
await page.waitForURL('http://127.0.0.1:3300/');
|
||||
const result = await page.evaluate(async () => {
|
||||
const api = window.CrankApi;
|
||||
const session = await api.getSession();
|
||||
const csrf = await api.refreshSessionCsrf();
|
||||
session.csrf_token = csrf.csrf_token; window.CrankAuth.replaceSession(session);
|
||||
const ws = session.current_workspace_id || session.memberships[0].workspace.id;
|
||||
const agents = await api.listAgents(ws);
|
||||
const list = Array.isArray(agents) ? agents : (agents.agents || agents.items);
|
||||
const source = list.find(a => a.latest_published_version != null);
|
||||
if (!source) throw new Error('No published fixture Agent');
|
||||
const sid = source.agent_id || source.id;
|
||||
const version = await fetch('/api/admin/workspaces/'+ws+'/agents/'+sid+'/versions/'+source.latest_published_version).then(r=>r.json());
|
||||
const bindings = version.bindings.map(b => ({operation_id:b.operation_id,operation_version:b.operation_version,tool_name:b.tool_name,tool_title:b.tool_title,tool_description_override:b.tool_description_override,enabled:b.enabled}));
|
||||
const created = await api.createAgent(ws,{slug:'retro-probe-'+Date.now(),display_name:'Retro probe',description:'Synthetic regression probe',instructions:{},tool_selection_policy:{}});
|
||||
const id = created.agent_id || created.id;
|
||||
await api.saveAgentBindings(ws,id,bindings);
|
||||
await api.publishAgent(ws,id,{version:1});
|
||||
const before=await api.getAgent(ws,id);
|
||||
const publishedBefore=await fetch('/api/admin/workspaces/'+ws+'/agents/'+id+'/versions/1').then(r=>r.json());
|
||||
let errorCode=null; let saved=null;
|
||||
try { saved=await api.saveAgentBindings(ws,id,bindings); } catch(e) { errorCode=e.errorCode || e.code || e.message; }
|
||||
const after=await api.getAgent(ws,id);
|
||||
const publishedAfter=await fetch('/api/admin/workspaces/'+ws+'/agents/'+id+'/versions/1').then(r=>r.json());
|
||||
return {before_draft:before.current_draft_version,after_draft:after.current_draft_version,saved_version:saved && saved.version,published_unchanged:JSON.stringify(publishedBefore)===JSON.stringify(publishedAfter),error:errorCode};
|
||||
});
|
||||
console.log(JSON.stringify(result));
|
||||
assert.equal(result.error,null); assert.equal(result.before_draft,1); assert.equal(result.after_draft,2); assert.equal(result.saved_version,2); assert.equal(result.published_unchanged,true);
|
||||
} finally { await browser.close(); }
|
||||
})().catch(e=>{console.error(e.message);process.exitCode=1;});
|
||||
@@ -0,0 +1,906 @@
|
||||
diff --git a/apps/admin-api/tests/integration.rs b/apps/admin-api/tests/integration.rs
|
||||
index eb3215b..a6ff2f7 100644
|
||||
--- a/apps/admin-api/tests/integration.rs
|
||||
+++ b/apps/admin-api/tests/integration.rs
|
||||
@@ -1,5 +1,6 @@
|
||||
mod integration {
|
||||
mod agent_catalog;
|
||||
+ mod agent_catalog_edit;
|
||||
mod auth_rate_limit;
|
||||
mod common;
|
||||
mod community_access_usage;
|
||||
diff --git a/apps/admin-api/tests/integration/agent_catalog_edit.rs b/apps/admin-api/tests/integration/agent_catalog_edit.rs
|
||||
new file mode 100644
|
||||
index 0000000..1986044
|
||||
--- /dev/null
|
||||
+++ b/apps/admin-api/tests/integration/agent_catalog_edit.rs
|
||||
@@ -0,0 +1,889 @@
|
||||
+use super::common::*;
|
||||
+
|
||||
+use crank_core::{Workspace, WorkspaceId, WorkspaceStatus};
|
||||
+use crank_registry::{CreateWorkspaceRequest, PostgresRegistry};
|
||||
+use serde_json::{Value, json};
|
||||
+use serial_test::serial;
|
||||
+use time::OffsetDateTime;
|
||||
+
|
||||
+const DEFAULT_WORKSPACE_ID: &str = "ws_default";
|
||||
+
|
||||
+fn binding(operation_id: &str, tool_name: &str, tool_title: &str) -> Value {
|
||||
+ json!({
|
||||
+ "operation_id": operation_id,
|
||||
+ "operation_version": 1,
|
||||
+ "tool_name": tool_name,
|
||||
+ "tool_title": tool_title,
|
||||
+ "tool_description_override": null,
|
||||
+ "enabled": true
|
||||
+ })
|
||||
+}
|
||||
+
|
||||
+async fn create_draft_operation(
|
||||
+ client: &reqwest::Client,
|
||||
+ base_url: &TestServer,
|
||||
+ upstream: &str,
|
||||
+ name: &str,
|
||||
+) -> String {
|
||||
+ let operation = assert_success_json(
|
||||
+ client
|
||||
+ .post(format!("{base_url}/operations"))
|
||||
+ .json(&test_operation_payload(upstream, name))
|
||||
+ .send()
|
||||
+ .await
|
||||
+ .unwrap(),
|
||||
+ )
|
||||
+ .await;
|
||||
+ operation["operation_id"].as_str().unwrap().to_owned()
|
||||
+}
|
||||
+
|
||||
+async fn create_published_operation(
|
||||
+ client: &reqwest::Client,
|
||||
+ base_url: &TestServer,
|
||||
+ upstream: &str,
|
||||
+ name: &str,
|
||||
+) -> String {
|
||||
+ let operation_id = create_draft_operation(client, base_url, upstream, name).await;
|
||||
+ let etag = operation_etag(client, base_url, &operation_id).await;
|
||||
+ assert_success_json(
|
||||
+ client
|
||||
+ .post(format!("{base_url}/operations/{operation_id}/publish"))
|
||||
+ .header(reqwest::header::IF_MATCH, etag)
|
||||
+ .json(&json!({ "version": 1 }))
|
||||
+ .send()
|
||||
+ .await
|
||||
+ .unwrap(),
|
||||
+ )
|
||||
+ .await;
|
||||
+ operation_id
|
||||
+}
|
||||
+
|
||||
+async fn create_published_agent(
|
||||
+ client: &reqwest::Client,
|
||||
+ base_url: &TestServer,
|
||||
+ slug: &str,
|
||||
+ operation_id: &str,
|
||||
+ tool_name: &str,
|
||||
+) -> (String, Value) {
|
||||
+ let agent = assert_success_json(
|
||||
+ client
|
||||
+ .post(format!("{base_url}/agents"))
|
||||
+ .json(&json!({
|
||||
+ "slug": slug,
|
||||
+ "display_name": slug,
|
||||
+ "description": "agent catalog edit fixture",
|
||||
+ "instructions": { "system_prompt": "Use only published bindings" },
|
||||
+ "tool_selection_policy": {}
|
||||
+ }))
|
||||
+ .send()
|
||||
+ .await
|
||||
+ .unwrap(),
|
||||
+ )
|
||||
+ .await;
|
||||
+ let agent_id = agent["agent_id"].as_str().unwrap().to_owned();
|
||||
+
|
||||
+ let etag = agent_etag(client, base_url, &agent_id).await;
|
||||
+ assert_success_json(
|
||||
+ client
|
||||
+ .post(format!("{base_url}/agents/{agent_id}/bindings"))
|
||||
+ .header(reqwest::header::IF_MATCH, etag)
|
||||
+ .json(&json!([binding(operation_id, tool_name, "Base Tool")]))
|
||||
+ .send()
|
||||
+ .await
|
||||
+ .unwrap(),
|
||||
+ )
|
||||
+ .await;
|
||||
+
|
||||
+ let etag = agent_etag(client, base_url, &agent_id).await;
|
||||
+ assert_success_json(
|
||||
+ client
|
||||
+ .post(format!("{base_url}/agents/{agent_id}/publish"))
|
||||
+ .header(reqwest::header::IF_MATCH, etag)
|
||||
+ .json(&json!({ "version": 1 }))
|
||||
+ .send()
|
||||
+ .await
|
||||
+ .unwrap(),
|
||||
+ )
|
||||
+ .await;
|
||||
+
|
||||
+ let published_v1 = assert_success_json(
|
||||
+ client
|
||||
+ .get(format!("{base_url}/agents/{agent_id}/versions/1"))
|
||||
+ .send()
|
||||
+ .await
|
||||
+ .unwrap(),
|
||||
+ )
|
||||
+ .await;
|
||||
+
|
||||
+ (agent_id, published_v1)
|
||||
+}
|
||||
+
|
||||
+async fn agent_version_count(db: &PostgresRegistry, agent_id: &str) -> i64 {
|
||||
+ sqlx::query_scalar("select count(*) from agent_versions where agent_id = $1")
|
||||
+ .bind(agent_id)
|
||||
+ .fetch_one(db.pool())
|
||||
+ .await
|
||||
+ .unwrap()
|
||||
+}
|
||||
+
|
||||
+async fn assert_no_durable_draft(
|
||||
+ client: &reqwest::Client,
|
||||
+ db: &PostgresRegistry,
|
||||
+ base_url: &TestServer,
|
||||
+ agent_id: &str,
|
||||
+ published_v1: &Value,
|
||||
+) {
|
||||
+ let summary = assert_success_json(
|
||||
+ client
|
||||
+ .get(format!("{base_url}/agents/{agent_id}"))
|
||||
+ .send()
|
||||
+ .await
|
||||
+ .unwrap(),
|
||||
+ )
|
||||
+ .await;
|
||||
+ assert_eq!(
|
||||
+ summary["current_draft_version"], 1,
|
||||
+ "a rejected edit must not fork a Draft Version: {summary}"
|
||||
+ );
|
||||
+ assert_eq!(summary["latest_published_version"], 1, "{summary}");
|
||||
+ assert_eq!(summary["status"], "published", "{summary}");
|
||||
+ assert_eq!(
|
||||
+ agent_version_count(db, agent_id).await,
|
||||
+ 1,
|
||||
+ "a rejected edit must not persist a new Agent Version row"
|
||||
+ );
|
||||
+
|
||||
+ let published_after = assert_success_json(
|
||||
+ client
|
||||
+ .get(format!("{base_url}/agents/{agent_id}/versions/1"))
|
||||
+ .send()
|
||||
+ .await
|
||||
+ .unwrap(),
|
||||
+ )
|
||||
+ .await;
|
||||
+ assert_eq!(
|
||||
+ &published_after, published_v1,
|
||||
+ "the Published snapshot and its bindings must stay unchanged after a rejected edit"
|
||||
+ );
|
||||
+}
|
||||
+
|
||||
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
+#[serial]
|
||||
+async fn published_agent_first_edit_forks_one_draft_and_keeps_published_snapshot() {
|
||||
+ let registry = test_registry().await;
|
||||
+ let db = registry.clone();
|
||||
+ let storage_root = test_storage_root("agent_catalog_edit_first");
|
||||
+ let upstream_base_url = spawn_upstream_server().await;
|
||||
+ let base_url = spawn_admin_api(build_test_app(registry, storage_root)).await;
|
||||
+ let client = authorized_client(&base_url).await;
|
||||
+
|
||||
+ let operation_id =
|
||||
+ create_published_operation(&client, &base_url, &upstream_base_url, "edit_first_tool").await;
|
||||
+ let (agent_id, published_v1) = create_published_agent(
|
||||
+ &client,
|
||||
+ &base_url,
|
||||
+ "edit-first",
|
||||
+ &operation_id,
|
||||
+ "edit_first_tool",
|
||||
+ )
|
||||
+ .await;
|
||||
+
|
||||
+ let summary_before = assert_success_json(
|
||||
+ client
|
||||
+ .get(format!("{base_url}/agents/{agent_id}"))
|
||||
+ .send()
|
||||
+ .await
|
||||
+ .unwrap(),
|
||||
+ )
|
||||
+ .await;
|
||||
+ assert_eq!(summary_before["current_draft_version"], 1);
|
||||
+ assert_eq!(summary_before["latest_published_version"], 1);
|
||||
+ assert_eq!(summary_before["status"], "published");
|
||||
+
|
||||
+ let desired_policy = json!({
|
||||
+ "mode": "search",
|
||||
+ "groups": [{
|
||||
+ "id": "crm-group",
|
||||
+ "name": "CRM",
|
||||
+ "description": "CRM tools",
|
||||
+ "tool_names": ["edit_first_tool"]
|
||||
+ }],
|
||||
+ "search": { "max_results": 5 }
|
||||
+ });
|
||||
+
|
||||
+ let edit_etag = agent_etag(&client, &base_url, &agent_id).await;
|
||||
+ let response = client
|
||||
+ .post(format!("{base_url}/agents/{agent_id}/bindings"))
|
||||
+ .header(reqwest::header::IF_MATCH, edit_etag)
|
||||
+ .json(&json!({
|
||||
+ "bindings": [binding(&operation_id, "edit_first_tool", "Edited Tool")],
|
||||
+ "tool_selection_policy": desired_policy
|
||||
+ }))
|
||||
+ .send()
|
||||
+ .await
|
||||
+ .unwrap();
|
||||
+ let status = response.status();
|
||||
+ let body = response.json::<Value>().await.unwrap();
|
||||
+ assert_eq!(
|
||||
+ status,
|
||||
+ reqwest::StatusCode::OK,
|
||||
+ "the first edit of a Published Agent must fork and save under the original If-Match: {body}"
|
||||
+ );
|
||||
+ assert_eq!(body["version"], 2, "{body}");
|
||||
+
|
||||
+ let summary_after = assert_success_json(
|
||||
+ client
|
||||
+ .get(format!("{base_url}/agents/{agent_id}"))
|
||||
+ .send()
|
||||
+ .await
|
||||
+ .unwrap(),
|
||||
+ )
|
||||
+ .await;
|
||||
+ assert_eq!(summary_after["current_draft_version"], 2, "{summary_after}");
|
||||
+ assert_eq!(
|
||||
+ summary_after["latest_published_version"], 1,
|
||||
+ "{summary_after}"
|
||||
+ );
|
||||
+ assert_eq!(summary_after["status"], "published", "{summary_after}");
|
||||
+
|
||||
+ assert_eq!(
|
||||
+ agent_version_count(&db, &agent_id).await,
|
||||
+ 2,
|
||||
+ "the first edit must create exactly one additional Draft Version"
|
||||
+ );
|
||||
+
|
||||
+ let draft = assert_success_json(
|
||||
+ client
|
||||
+ .get(format!("{base_url}/agents/{agent_id}/versions/2"))
|
||||
+ .send()
|
||||
+ .await
|
||||
+ .unwrap(),
|
||||
+ )
|
||||
+ .await;
|
||||
+ assert_eq!(draft["status"], "draft", "{draft}");
|
||||
+ assert_eq!(
|
||||
+ draft["snapshot"]["instructions"],
|
||||
+ published_v1["snapshot"]["instructions"]
|
||||
+ );
|
||||
+ assert_eq!(draft["bindings"].as_array().unwrap().len(), 1, "{draft}");
|
||||
+ assert_eq!(draft["bindings"][0]["tool_title"], "Edited Tool", "{draft}");
|
||||
+ assert_eq!(
|
||||
+ draft["snapshot"]["tool_selection_policy"]["mode"], "search",
|
||||
+ "{draft}"
|
||||
+ );
|
||||
+ assert_eq!(
|
||||
+ draft["snapshot"]["tool_selection_policy"]["search"]["max_results"], 5,
|
||||
+ "{draft}"
|
||||
+ );
|
||||
+
|
||||
+ let published_after = assert_success_json(
|
||||
+ client
|
||||
+ .get(format!("{base_url}/agents/{agent_id}/versions/1"))
|
||||
+ .send()
|
||||
+ .await
|
||||
+ .unwrap(),
|
||||
+ )
|
||||
+ .await;
|
||||
+ assert_eq!(
|
||||
+ published_after, published_v1,
|
||||
+ "the Published v1 snapshot must not change when the Draft is forked"
|
||||
+ );
|
||||
+
|
||||
+ let next_etag = agent_etag(&client, &base_url, &agent_id).await;
|
||||
+ let second_response = client
|
||||
+ .post(format!("{base_url}/agents/{agent_id}/bindings"))
|
||||
+ .header(reqwest::header::IF_MATCH, next_etag)
|
||||
+ .json(&json!({
|
||||
+ "bindings": [binding(&operation_id, "edit_first_tool", "Edited Again")],
|
||||
+ "tool_selection_policy": desired_policy
|
||||
+ }))
|
||||
+ .send()
|
||||
+ .await
|
||||
+ .unwrap();
|
||||
+ let second_status = second_response.status();
|
||||
+ let second_body = second_response.text().await.unwrap();
|
||||
+ assert_eq!(
|
||||
+ second_status,
|
||||
+ reqwest::StatusCode::OK,
|
||||
+ "a subsequent valid edit on the Draft must succeed: {second_body}"
|
||||
+ );
|
||||
+ assert_eq!(
|
||||
+ agent_version_count(&db, &agent_id).await,
|
||||
+ 2,
|
||||
+ "a subsequent valid edit must stay on the existing Draft v2"
|
||||
+ );
|
||||
+}
|
||||
+
|
||||
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
+#[serial]
|
||||
+async fn rejected_invalid_policy_leaves_no_durable_draft() {
|
||||
+ let registry = test_registry().await;
|
||||
+ let db = registry.clone();
|
||||
+ let storage_root = test_storage_root("agent_catalog_edit_invalid_policy");
|
||||
+ let upstream_base_url = spawn_upstream_server().await;
|
||||
+ let base_url = spawn_admin_api(build_test_app(registry, storage_root)).await;
|
||||
+ let client = authorized_client(&base_url).await;
|
||||
+
|
||||
+ let operation_id =
|
||||
+ create_published_operation(&client, &base_url, &upstream_base_url, "edit_policy_tool")
|
||||
+ .await;
|
||||
+ let (agent_id, published_v1) = create_published_agent(
|
||||
+ &client,
|
||||
+ &base_url,
|
||||
+ "edit-policy",
|
||||
+ &operation_id,
|
||||
+ "edit_policy_tool",
|
||||
+ )
|
||||
+ .await;
|
||||
+
|
||||
+ let etag = agent_etag(&client, &base_url, &agent_id).await;
|
||||
+ let response = client
|
||||
+ .post(format!("{base_url}/agents/{agent_id}/bindings"))
|
||||
+ .header(reqwest::header::IF_MATCH, etag)
|
||||
+ .json(&json!({
|
||||
+ "bindings": [],
|
||||
+ "tool_selection_policy": {
|
||||
+ "mode": "direct",
|
||||
+ "groups": [{
|
||||
+ "id": "group-1",
|
||||
+ "name": "Group",
|
||||
+ "description": "groups require search mode",
|
||||
+ "tool_names": []
|
||||
+ }]
|
||||
+ }
|
||||
+ }))
|
||||
+ .send()
|
||||
+ .await
|
||||
+ .unwrap();
|
||||
+ let status = response.status();
|
||||
+ let body = response.text().await.unwrap();
|
||||
+ assert_eq!(
|
||||
+ status,
|
||||
+ reqwest::StatusCode::BAD_REQUEST,
|
||||
+ "a grouping policy in direct mode must be rejected: {body}"
|
||||
+ );
|
||||
+
|
||||
+ assert_no_durable_draft(&client, &db, &base_url, &agent_id, &published_v1).await;
|
||||
+}
|
||||
+
|
||||
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
+#[serial]
|
||||
+async fn rejected_unpublished_operation_leaves_no_durable_draft() {
|
||||
+ let registry = test_registry().await;
|
||||
+ let db = registry.clone();
|
||||
+ let storage_root = test_storage_root("agent_catalog_edit_draft_op");
|
||||
+ let upstream_base_url = spawn_upstream_server().await;
|
||||
+ let base_url = spawn_admin_api(build_test_app(registry, storage_root)).await;
|
||||
+ let client = authorized_client(&base_url).await;
|
||||
+
|
||||
+ let live_operation =
|
||||
+ create_published_operation(&client, &base_url, &upstream_base_url, "edit_live_tool").await;
|
||||
+ let (agent_id, published_v1) = create_published_agent(
|
||||
+ &client,
|
||||
+ &base_url,
|
||||
+ "edit-draft-op",
|
||||
+ &live_operation,
|
||||
+ "edit_live_tool",
|
||||
+ )
|
||||
+ .await;
|
||||
+
|
||||
+ let draft_operation =
|
||||
+ create_draft_operation(&client, &base_url, &upstream_base_url, "edit_draft_tool").await;
|
||||
+
|
||||
+ let etag = agent_etag(&client, &base_url, &agent_id).await;
|
||||
+ let response = client
|
||||
+ .post(format!("{base_url}/agents/{agent_id}/bindings"))
|
||||
+ .header(reqwest::header::IF_MATCH, etag)
|
||||
+ .json(&json!([binding(
|
||||
+ &draft_operation,
|
||||
+ "edit_draft_tool",
|
||||
+ "Draft Tool"
|
||||
+ )]))
|
||||
+ .send()
|
||||
+ .await
|
||||
+ .unwrap();
|
||||
+ let status = response.status();
|
||||
+ let body = response.text().await.unwrap();
|
||||
+ assert_eq!(
|
||||
+ status,
|
||||
+ reqwest::StatusCode::UNPROCESSABLE_ENTITY,
|
||||
+ "binding an unpublished Operation must be rejected: {body}"
|
||||
+ );
|
||||
+ let body: Value = serde_json::from_str(&body).unwrap();
|
||||
+ assert_eq!(
|
||||
+ body["error"]["code"], "agent_binding_not_published",
|
||||
+ "{body}"
|
||||
+ );
|
||||
+
|
||||
+ assert_no_durable_draft(&client, &db, &base_url, &agent_id, &published_v1).await;
|
||||
+}
|
||||
+
|
||||
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
+#[serial]
|
||||
+async fn rejected_archived_operation_leaves_no_durable_draft() {
|
||||
+ let registry = test_registry().await;
|
||||
+ let db = registry.clone();
|
||||
+ let storage_root = test_storage_root("agent_catalog_edit_archived_op");
|
||||
+ let upstream_base_url = spawn_upstream_server().await;
|
||||
+ let base_url = spawn_admin_api(build_test_app(registry, storage_root)).await;
|
||||
+ let client = authorized_client(&base_url).await;
|
||||
+
|
||||
+ let live_operation = create_published_operation(
|
||||
+ &client,
|
||||
+ &base_url,
|
||||
+ &upstream_base_url,
|
||||
+ "edit_live_tool_arch",
|
||||
+ )
|
||||
+ .await;
|
||||
+ let (agent_id, published_v1) = create_published_agent(
|
||||
+ &client,
|
||||
+ &base_url,
|
||||
+ "edit-archived-op",
|
||||
+ &live_operation,
|
||||
+ "edit_live_tool_arch",
|
||||
+ )
|
||||
+ .await;
|
||||
+
|
||||
+ let archived_operation =
|
||||
+ create_published_operation(&client, &base_url, &upstream_base_url, "edit_archived_tool")
|
||||
+ .await;
|
||||
+ let operation_etag = operation_etag(&client, &base_url, &archived_operation).await;
|
||||
+ let archived = client
|
||||
+ .post(format!(
|
||||
+ "{base_url}/operations/{archived_operation}/archive"
|
||||
+ ))
|
||||
+ .header(reqwest::header::IF_MATCH, operation_etag)
|
||||
+ .send()
|
||||
+ .await
|
||||
+ .unwrap();
|
||||
+ let archived_status = archived.status();
|
||||
+ let archived_body = archived.text().await.unwrap();
|
||||
+ assert!(archived_status.is_success(), "{archived_body}");
|
||||
+
|
||||
+ let etag = agent_etag(&client, &base_url, &agent_id).await;
|
||||
+ let response = client
|
||||
+ .post(format!("{base_url}/agents/{agent_id}/bindings"))
|
||||
+ .header(reqwest::header::IF_MATCH, etag)
|
||||
+ .json(&json!([binding(
|
||||
+ &archived_operation,
|
||||
+ "edit_archived_tool",
|
||||
+ "Archived Tool"
|
||||
+ )]))
|
||||
+ .send()
|
||||
+ .await
|
||||
+ .unwrap();
|
||||
+ let status = response.status();
|
||||
+ let body = response.text().await.unwrap();
|
||||
+ assert_eq!(
|
||||
+ status,
|
||||
+ reqwest::StatusCode::UNPROCESSABLE_ENTITY,
|
||||
+ "binding an archived Operation must be rejected: {body}"
|
||||
+ );
|
||||
+ let body: Value = serde_json::from_str(&body).unwrap();
|
||||
+ assert_eq!(
|
||||
+ body["error"]["code"], "agent_binding_archived_operation",
|
||||
+ "{body}"
|
||||
+ );
|
||||
+
|
||||
+ assert_no_durable_draft(&client, &db, &base_url, &agent_id, &published_v1).await;
|
||||
+}
|
||||
+
|
||||
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
+#[serial]
|
||||
+async fn rejected_foreign_operation_leaves_no_durable_draft() {
|
||||
+ let registry = test_registry().await;
|
||||
+ let db = registry.clone();
|
||||
+ let storage_root = test_storage_root("agent_catalog_edit_foreign_op");
|
||||
+ let upstream_base_url = spawn_upstream_server().await;
|
||||
+ let base_url = spawn_admin_api(build_test_app(registry.clone(), storage_root)).await;
|
||||
+ let client = authorized_client(&base_url).await;
|
||||
+
|
||||
+ let live_operation = create_published_operation(
|
||||
+ &client,
|
||||
+ &base_url,
|
||||
+ &upstream_base_url,
|
||||
+ "edit_live_tool_foreign",
|
||||
+ )
|
||||
+ .await;
|
||||
+ let (agent_id, published_v1) = create_published_agent(
|
||||
+ &client,
|
||||
+ &base_url,
|
||||
+ "edit-foreign-op",
|
||||
+ &live_operation,
|
||||
+ "edit_live_tool_foreign",
|
||||
+ )
|
||||
+ .await;
|
||||
+
|
||||
+ let foreign_workspace = WorkspaceId::new("ws_agent_edit_foreign");
|
||||
+ let now = OffsetDateTime::now_utc();
|
||||
+ db.create_workspace(CreateWorkspaceRequest {
|
||||
+ workspace: &Workspace {
|
||||
+ id: foreign_workspace.clone(),
|
||||
+ slug: "agent-edit-foreign".to_owned(),
|
||||
+ display_name: "Agent Edit Foreign".to_owned(),
|
||||
+ status: WorkspaceStatus::Active,
|
||||
+ settings: json!({}),
|
||||
+ created_at: now,
|
||||
+ updated_at: now,
|
||||
+ },
|
||||
+ })
|
||||
+ .await
|
||||
+ .unwrap();
|
||||
+
|
||||
+ let foreign_service = test_service(
|
||||
+ db.clone(),
|
||||
+ test_storage_root("agent_catalog_edit_foreign_service"),
|
||||
+ test_auth_settings(),
|
||||
+ test_secret_crypto(),
|
||||
+ );
|
||||
+ let foreign_operation = foreign_service
|
||||
+ .create_operation(
|
||||
+ &foreign_workspace,
|
||||
+ test_operation_payload(&upstream_base_url, "edit_foreign_tool"),
|
||||
+ )
|
||||
+ .await
|
||||
+ .unwrap();
|
||||
+ let foreign_operation_id = foreign_operation.operation_id;
|
||||
+
|
||||
+ let etag = agent_etag(&client, &base_url, &agent_id).await;
|
||||
+ let response = client
|
||||
+ .post(format!("{base_url}/agents/{agent_id}/bindings"))
|
||||
+ .header(reqwest::header::IF_MATCH, etag)
|
||||
+ .json(&json!([binding(
|
||||
+ &foreign_operation_id,
|
||||
+ "edit_foreign_tool",
|
||||
+ "Foreign Tool"
|
||||
+ )]))
|
||||
+ .send()
|
||||
+ .await
|
||||
+ .unwrap();
|
||||
+ let status = response.status();
|
||||
+ let body = response.text().await.unwrap();
|
||||
+ assert_eq!(
|
||||
+ status,
|
||||
+ reqwest::StatusCode::NOT_FOUND,
|
||||
+ "binding an Operation from another workspace must be rejected: {body}"
|
||||
+ );
|
||||
+ let body: Value = serde_json::from_str(&body).unwrap();
|
||||
+ assert_eq!(
|
||||
+ body["error"]["code"], "agent_binding_scope_denied",
|
||||
+ "{body}"
|
||||
+ );
|
||||
+
|
||||
+ assert_no_durable_draft(&client, &db, &base_url, &agent_id, &published_v1).await;
|
||||
+}
|
||||
+
|
||||
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
+#[serial]
|
||||
+async fn concurrent_first_edits_with_same_etag_have_one_winner() {
|
||||
+ let registry = test_registry().await;
|
||||
+ let db = registry.clone();
|
||||
+ let storage_root = test_storage_root("agent_catalog_edit_concurrent");
|
||||
+ let upstream_base_url = spawn_upstream_server().await;
|
||||
+ let base_url = spawn_admin_api(build_test_app(registry, storage_root)).await;
|
||||
+ let client = authorized_client(&base_url).await;
|
||||
+
|
||||
+ let operation_id =
|
||||
+ create_published_operation(&client, &base_url, &upstream_base_url, "edit_race_tool").await;
|
||||
+ let (agent_id, published_v1) = create_published_agent(
|
||||
+ &client,
|
||||
+ &base_url,
|
||||
+ "edit-race",
|
||||
+ &operation_id,
|
||||
+ "edit_race_tool",
|
||||
+ )
|
||||
+ .await;
|
||||
+
|
||||
+ // Single original precondition taken once from the Published state.
|
||||
+ let original_etag = agent_etag(&client, &base_url, &agent_id).await;
|
||||
+ let endpoint = format!("{base_url}/agents/{agent_id}/bindings");
|
||||
+ let payload_a = json!([binding(&operation_id, "edit_race_tool", "Race Winner A")]);
|
||||
+ let payload_b = json!([binding(&operation_id, "edit_race_tool", "Race Winner B")]);
|
||||
+
|
||||
+ let spawn_edit = |payload: Value, etag: String, endpoint: String| {
|
||||
+ let client = client.clone();
|
||||
+ tokio::spawn(async move {
|
||||
+ let response = client
|
||||
+ .post(endpoint)
|
||||
+ .header(reqwest::header::IF_MATCH, etag)
|
||||
+ .json(&payload)
|
||||
+ .send()
|
||||
+ .await
|
||||
+ .unwrap();
|
||||
+ let status = response.status();
|
||||
+ let body = response.json::<Value>().await.unwrap();
|
||||
+ (status, body)
|
||||
+ })
|
||||
+ };
|
||||
+
|
||||
+ let first = spawn_edit(payload_a, original_etag.clone(), endpoint.clone());
|
||||
+ let second = spawn_edit(payload_b, original_etag, endpoint);
|
||||
+ let (first, second) = tokio::join!(first, second);
|
||||
+ let results = vec![first.unwrap(), second.unwrap()];
|
||||
+
|
||||
+ let successes = results
|
||||
+ .iter()
|
||||
+ .filter(|(status, _)| status.is_success())
|
||||
+ .count();
|
||||
+ let conflicts = results
|
||||
+ .iter()
|
||||
+ .filter(|(status, _)| *status == reqwest::StatusCode::CONFLICT)
|
||||
+ .count();
|
||||
+ assert_eq!(
|
||||
+ successes, 1,
|
||||
+ "exactly one concurrent first edit must win: {results:?}"
|
||||
+ );
|
||||
+ assert_eq!(
|
||||
+ conflicts, 1,
|
||||
+ "the losing concurrent first edit must report a stable conflict: {results:?}"
|
||||
+ );
|
||||
+
|
||||
+ let conflict_body = results
|
||||
+ .iter()
|
||||
+ .find(|(status, _)| *status == reqwest::StatusCode::CONFLICT)
|
||||
+ .map(|(_, body)| body)
|
||||
+ .unwrap();
|
||||
+ assert_eq!(
|
||||
+ conflict_body["error"]["code"], "agent_stale_revision",
|
||||
+ "{conflict_body}"
|
||||
+ );
|
||||
+
|
||||
+ let summary = assert_success_json(
|
||||
+ client
|
||||
+ .get(format!("{base_url}/agents/{agent_id}"))
|
||||
+ .send()
|
||||
+ .await
|
||||
+ .unwrap(),
|
||||
+ )
|
||||
+ .await;
|
||||
+ assert_eq!(summary["current_draft_version"], 2, "{summary}");
|
||||
+ assert_eq!(summary["latest_published_version"], 1, "{summary}");
|
||||
+ assert_eq!(
|
||||
+ agent_version_count(&db, &agent_id).await,
|
||||
+ 2,
|
||||
+ "the losing concurrent edit must not fork a second Draft"
|
||||
+ );
|
||||
+
|
||||
+ let published_after = assert_success_json(
|
||||
+ client
|
||||
+ .get(format!("{base_url}/agents/{agent_id}/versions/1"))
|
||||
+ .send()
|
||||
+ .await
|
||||
+ .unwrap(),
|
||||
+ )
|
||||
+ .await;
|
||||
+ assert_eq!(published_after, published_v1);
|
||||
+}
|
||||
+
|
||||
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
+#[serial]
|
||||
+async fn first_edit_after_operation_archive_leaves_no_durable_draft() {
|
||||
+ let registry = test_registry().await;
|
||||
+ let db = registry.clone();
|
||||
+ let storage_root = test_storage_root("agent_catalog_edit_archive_ordering");
|
||||
+ let upstream_base_url = spawn_upstream_server().await;
|
||||
+ let base_url = spawn_admin_api(build_test_app(registry, storage_root)).await;
|
||||
+ let client = authorized_client(&base_url).await;
|
||||
+
|
||||
+ let live_operation =
|
||||
+ create_published_operation(&client, &base_url, &upstream_base_url, "edit_order_live").await;
|
||||
+ let (agent_id, published_v1) = create_published_agent(
|
||||
+ &client,
|
||||
+ &base_url,
|
||||
+ "edit-order",
|
||||
+ &live_operation,
|
||||
+ "edit_order_live",
|
||||
+ )
|
||||
+ .await;
|
||||
+
|
||||
+ let archived_operation = create_published_operation(
|
||||
+ &client,
|
||||
+ &base_url,
|
||||
+ &upstream_base_url,
|
||||
+ "edit_order_archived",
|
||||
+ )
|
||||
+ .await;
|
||||
+ let operation_etag = operation_etag(&client, &base_url, &archived_operation).await;
|
||||
+ let archived = client
|
||||
+ .post(format!(
|
||||
+ "{base_url}/operations/{archived_operation}/archive"
|
||||
+ ))
|
||||
+ .header(reqwest::header::IF_MATCH, operation_etag)
|
||||
+ .send()
|
||||
+ .await
|
||||
+ .unwrap();
|
||||
+ let archived_status = archived.status();
|
||||
+ let archived_body = archived.text().await.unwrap();
|
||||
+ assert!(archived_status.is_success(), "{archived_body}");
|
||||
+
|
||||
+ let etag = agent_etag(&client, &base_url, &agent_id).await;
|
||||
+ let response = client
|
||||
+ .post(format!("{base_url}/agents/{agent_id}/bindings"))
|
||||
+ .header(reqwest::header::IF_MATCH, etag)
|
||||
+ .json(&json!([binding(
|
||||
+ &archived_operation,
|
||||
+ "edit_order_archived",
|
||||
+ "Archived Order Tool"
|
||||
+ )]))
|
||||
+ .send()
|
||||
+ .await
|
||||
+ .unwrap();
|
||||
+ let status = response.status();
|
||||
+ let body = response.text().await.unwrap();
|
||||
+ assert!(
|
||||
+ status.is_client_error(),
|
||||
+ "a first edit that references an archived Operation must be rejected: {status}: {body}"
|
||||
+ );
|
||||
+
|
||||
+ assert_no_durable_draft(&client, &db, &base_url, &agent_id, &published_v1).await;
|
||||
+}
|
||||
+
|
||||
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
+#[serial]
|
||||
+async fn first_edit_rejects_when_operation_archives_during_save() {
|
||||
+ let registry = test_registry().await;
|
||||
+ let db = registry.clone();
|
||||
+ let storage_root = test_storage_root("agent_catalog_edit_archive_race");
|
||||
+ let upstream_base_url = spawn_upstream_server().await;
|
||||
+ let base_url = spawn_admin_api(build_test_app(registry, storage_root)).await;
|
||||
+ let client = authorized_client(&base_url).await;
|
||||
+
|
||||
+ let live_operation =
|
||||
+ create_published_operation(&client, &base_url, &upstream_base_url, "edit_race_live").await;
|
||||
+ let (agent_id, published_v1) = create_published_agent(
|
||||
+ &client,
|
||||
+ &base_url,
|
||||
+ "edit-archive-race",
|
||||
+ &live_operation,
|
||||
+ "edit_race_live",
|
||||
+ )
|
||||
+ .await;
|
||||
+
|
||||
+ let target_operation =
|
||||
+ create_published_operation(&client, &base_url, &upstream_base_url, "edit_race_target")
|
||||
+ .await;
|
||||
+
|
||||
+ // Read the edit precondition before taking the Operation lock; Agent detail
|
||||
+ // may itself inspect bound Operations.
|
||||
+ let etag_response = client
|
||||
+ .get(format!("{base_url}/agents/{agent_id}"))
|
||||
+ .send()
|
||||
+ .await
|
||||
+ .unwrap();
|
||||
+ let etag_status = etag_response.status();
|
||||
+ let etag = etag_response
|
||||
+ .headers()
|
||||
+ .get(reqwest::header::ETAG)
|
||||
+ .and_then(|value| value.to_str().ok())
|
||||
+ .map(str::to_owned);
|
||||
+ let etag_body = etag_response.text().await.unwrap();
|
||||
+ assert_eq!(
|
||||
+ etag_status,
|
||||
+ reqwest::StatusCode::OK,
|
||||
+ "reading the Agent ETag before the archive race must succeed: {etag_body}"
|
||||
+ );
|
||||
+ let etag = etag.expect("Agent detail must expose an ETag");
|
||||
+
|
||||
+ // Use an independent pool for the holder and pg_stat_activity monitor. The
|
||||
+ // fixture registry has one connection, which the request needs to reach the
|
||||
+ // Operation lock wait.
|
||||
+ let lock_registry =
|
||||
+ PostgresRegistry::connect_with_options((*db.pool().connect_options()).clone())
|
||||
+ .await
|
||||
+ .unwrap();
|
||||
+
|
||||
+ // Hold the target Operation row lock from a separate connection so the edit
|
||||
+ // transaction cannot complete its binding write until the archive wins.
|
||||
+ let mut holder = lock_registry.pool().begin().await.unwrap();
|
||||
+ sqlx::query("select id from operations where workspace_id = $1 and id = $2 for update")
|
||||
+ .bind(DEFAULT_WORKSPACE_ID)
|
||||
+ .bind(&target_operation)
|
||||
+ .fetch_one(&mut *holder)
|
||||
+ .await
|
||||
+ .unwrap();
|
||||
+ let holder_pid: i32 = sqlx::query_scalar("select pg_backend_pid()")
|
||||
+ .fetch_one(&mut *holder)
|
||||
+ .await
|
||||
+ .unwrap();
|
||||
+ let edit_client = client.clone();
|
||||
+ let endpoint = format!("{base_url}/agents/{agent_id}/bindings");
|
||||
+ let edit_target = target_operation.clone();
|
||||
+ let edit = tokio::spawn(async move {
|
||||
+ let response = edit_client
|
||||
+ .post(endpoint)
|
||||
+ .header(reqwest::header::IF_MATCH, etag)
|
||||
+ .json(&json!([binding(
|
||||
+ &edit_target,
|
||||
+ "edit_race_target",
|
||||
+ "Archive Race Tool"
|
||||
+ )]))
|
||||
+ .send()
|
||||
+ .await
|
||||
+ .unwrap();
|
||||
+ let status = response.status();
|
||||
+ let body = response.text().await.unwrap();
|
||||
+ (status, body)
|
||||
+ });
|
||||
+
|
||||
+ // Wait for PostgreSQL to report the request blocked by this exact holder.
|
||||
+ // If the request completes first (the baseline CAS path), keep going so the
|
||||
+ // durable-draft assertion below reports that regression directly.
|
||||
+ let lock_wait = async {
|
||||
+ loop {
|
||||
+ if edit.is_finished() {
|
||||
+ return false;
|
||||
+ }
|
||||
+ let blocked: bool = sqlx::query_scalar(
|
||||
+ "select exists (
|
||||
+ select 1
|
||||
+ from pg_stat_activity
|
||||
+ where wait_event_type = 'Lock'
|
||||
+ and $1 = any(pg_blocking_pids(pid))
|
||||
+ and query ilike '%select status from operations%'
|
||||
+ )",
|
||||
+ )
|
||||
+ .bind(holder_pid)
|
||||
+ .fetch_one(lock_registry.pool())
|
||||
+ .await
|
||||
+ .unwrap();
|
||||
+ if blocked {
|
||||
+ return true;
|
||||
+ }
|
||||
+ tokio::task::yield_now().await;
|
||||
+ }
|
||||
+ };
|
||||
+ let saw_operation_lock_wait =
|
||||
+ match tokio::time::timeout(std::time::Duration::from_secs(10), lock_wait).await {
|
||||
+ Ok(saw_wait) => saw_wait,
|
||||
+ Err(_) => {
|
||||
+ edit.abort();
|
||||
+ holder.rollback().await.unwrap();
|
||||
+ let _ = edit.await;
|
||||
+ panic!("timed out waiting for the edit to block on the held Operation row lock");
|
||||
+ }
|
||||
+ };
|
||||
+
|
||||
+ sqlx::query(
|
||||
+ "update operations
|
||||
+ set status = 'archived', updated_at = now()
|
||||
+ where workspace_id = $1 and id = $2",
|
||||
+ )
|
||||
+ .bind(DEFAULT_WORKSPACE_ID)
|
||||
+ .bind(&target_operation)
|
||||
+ .execute(&mut *holder)
|
||||
+ .await
|
||||
+ .unwrap();
|
||||
+ holder.commit().await.unwrap();
|
||||
+
|
||||
+ let (status, body) = edit.await.unwrap();
|
||||
+ assert!(
|
||||
+ status.is_client_error(),
|
||||
+ "an edit racing an Operation archive must be rejected: {status}: {body}"
|
||||
+ );
|
||||
+
|
||||
+ assert_no_durable_draft(&client, &db, &base_url, &agent_id, &published_v1).await;
|
||||
+ assert!(
|
||||
+ saw_operation_lock_wait,
|
||||
+ "a corrected save path must wait on the holder's Operation row lock before archive commits"
|
||||
+ );
|
||||
+}
|
||||
@@ -0,0 +1,3 @@
|
||||
Running tests/integration.rs (local-build/red-target/debug/deps/integration-1fc3e84c91321bef)
|
||||
running 8 tests
|
||||
test result: FAILED. 0 passed; 8 failed; 0 ignored; 0 measured; 140 filtered out; finished in 53.48s
|
||||
@@ -0,0 +1,11 @@
|
||||
error: vendor/sqlx-core/LICENSE-APACHE:1: forbidden marker `commercial` # community-scope: allow=commercial
|
||||
error: vendor/sqlx-core/src/migrate.rs:1: forbidden marker `tenant` # community-scope: allow=tenant
|
||||
error: vendor/sqlx-core/src/pool/options.rs:1: forbidden marker `billing` # community-scope: allow=billing
|
||||
Ran 22 tests in 5.096s
|
||||
FAILED (failures=1)
|
||||
Community scope check failed:
|
||||
error: vendor/sqlx-core/LICENSE-APACHE:162: forbidden marker `commercial` # community-scope: allow=commercial
|
||||
error: vendor/sqlx-core/src/config/migrate.rs:40: forbidden marker `tenant` # community-scope: allow=tenant
|
||||
error: vendor/sqlx-core/src/config/reference.toml:178: forbidden marker `tenant` # community-scope: allow=tenant
|
||||
error: vendor/sqlx-core/src/migrate/migrator.rs:101: forbidden marker `tenant` # community-scope: allow=tenant
|
||||
error: vendor/sqlx-core/src/pool/options.rs:299: forbidden marker `billing` # community-scope: allow=billing
|
||||
@@ -0,0 +1,66 @@
|
||||
npm notice run e2e
|
||||
npm notice run playwright test --workers=1 --retries=0
|
||||
|
||||
Running 57 tests using 1 worker
|
||||
|
||||
(node:263735) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
|
||||
(Use `node --trace-warnings ...` to show where the warning was created)
|
||||
✓ 1 [chromium] › tests/e2e/agents.spec.js:4:1 › agents page shows demo cards and edit drawer opens (3.0s)
|
||||
✓ 2 [chromium] › tests/e2e/agents.spec.js:28:1 › agent drawer configures on-demand tool discovery and catalog sections (3.5s)
|
||||
✓ 3 [chromium] › tests/e2e/agents.spec.js:51:1 › agent lifecycle stale conflict shows localized recovery message (2.2s)
|
||||
✓ 4 [chromium] › tests/e2e/api-keys.spec.js:4:1 › api keys page opens create key flow (3.7s)
|
||||
✓ 5 [chromium] › tests/e2e/api-keys.spec.js:65:1 › failed clipboard write preserves one-time key material (2.6s) # community-scope: allow=one-time-token
|
||||
✓ 6 [chromium] › tests/e2e/api-keys.spec.js:101:1 › ambiguous create failure reconciles metadata before deliberate retry (2.9s)
|
||||
✓ 7 [chromium] › tests/e2e/api-keys.spec.js:136:1 › stale create response reconciles metadata without changing a newer modal generation (2.8s)
|
||||
✓ 8 [chromium] › tests/e2e/api-keys.spec.js:217:1 › duplicate key revoke and delete clicks send one request while the first request is pending (2.8s)
|
||||
✓ 9 [chromium] › tests/e2e/approvals.spec.js:4:1 › logs approval panel renders safe pending approval metadata (2.4s)
|
||||
✓ 10 [chromium] › tests/e2e/login-readiness.spec.js:4:1 › login helper leaves a ready CSRF session under a delayed csrf refresh (2.1s)
|
||||
✓ 11 [chromium] › tests/e2e/login.spec.js:41:1 › login page rejects invalid credentials (912ms)
|
||||
✓ 12 [chromium] › tests/e2e/login.spec.js:49:1 › login page signs in and redirects to operations (1.1s)
|
||||
✓ 13 [chromium] › tests/e2e/login.spec.js:81:1 › login page switches to bootstrap mode and submits one-time token (979ms) # community-scope: allow=one-time-token
|
||||
✓ 14 [chromium] › tests/e2e/login.spec.js:107:1 › CrankApi attaches csrf token to unsafe auth requests (478ms)
|
||||
✓ 15 [chromium] › tests/e2e/logs-usage.spec.js:4:1 › logs and usage pages show seeded data (2.4s)
|
||||
✓ 16 [chromium] › tests/e2e/observability.spec.js:4:1 › shell and wizard expose stable diagnostics hooks (2.5s)
|
||||
✓ 17 [chromium] › tests/e2e/observability.spec.js:19:1 › secrets page exposes stable secret management hooks (2.0s)
|
||||
✓ 18 [chromium] › tests/e2e/observability.spec.js:32:1 › API errors retain only bounded canonical support identities (1.5s)
|
||||
✓ 19 [chromium] › tests/e2e/onboarding.spec.js:70:1 › optional Getting Started checklist is server-derived, resumable, bilingual and accessible (3.8s)
|
||||
✓ 20 [chromium] › tests/e2e/onboarding.spec.js:136:1 › onboarding error exposes safe support correlation and retries without a client completion bypass (2.2s)
|
||||
✓ 21 [chromium] › tests/e2e/onboarding.spec.js:176:1 › validation, upstream and compatibility errors recover from the last authoritative onboarding step (2.5s)
|
||||
✓ 22 [chromium] › tests/e2e/onboarding.spec.js:222:1 › authentication recovery returns to an incomplete authoritative onboarding projection (3.1s)
|
||||
✓ 23 [chromium] › tests/e2e/onboarding.spec.js:250:1 › a BroadcastChannel refresh updates a second open tab from server progress (2.8s)
|
||||
✓ 24 [chromium] › tests/e2e/onboarding.spec.js:276:1 › bursty browser refresh signals coalesce into one request plus one trailing refresh (1.9s)
|
||||
✓ 25 [chromium] › tests/e2e/onboarding.spec.js:336:1 › stale onboarding deep link requires server reset before explicit reselection (2.7s)
|
||||
✓ 26 [chromium] › tests/e2e/onboarding.spec.js:371:1 › one-time key connection config is never recoverable after the reveal is lost (3.0s) # community-scope: allow=one-time-token
|
||||
✓ 27 [chromium] › tests/e2e/onboarding.spec.js:410:1 › first value is proven only by a real tools/call through the public MCP endpoint (11.6s)
|
||||
✓ 28 [chromium] › tests/e2e/operation-lifecycle.spec.js:4:1 › Operation lifecycle keeps published versions immutable and exposes safe correlation (2.8s)
|
||||
✓ 29 [chromium] › tests/e2e/operation-lifecycle.spec.js:132:3 › catalog lifecycle actions are state-aware in ru (3.6s)
|
||||
✓ 30 [chromium] › tests/e2e/operation-lifecycle.spec.js:132:3 › catalog lifecycle actions are state-aware in en (3.3s)
|
||||
✓ 31 [chromium] › tests/e2e/operations.spec.js:14:1 › operations page shows demo catalog and filter works (1.8s)
|
||||
✓ 32 [chromium] › tests/e2e/operations.spec.js:26:1 › operations page imports OpenAPI methods as drafts (3.3s)
|
||||
✓ 33 [chromium] › tests/e2e/operations.spec.js:144:1 › OpenAPI upload rejects invalid files locally and restores focus after Escape (3.1s)
|
||||
✓ 34 [chromium] › tests/e2e/operations.spec.js:210:1 › OpenAPI upload recovers from pagehide and a preview server error (2.1s)
|
||||
✓ 35 [chromium] › tests/e2e/operations.spec.js:245:1 › OpenAPI apply cancellation preserves the import job for an idempotent retry (4.2s)
|
||||
✓ 36 [chromium] › tests/e2e/operations.spec.js:344:1 › OpenAPI apply preserves job authority after language or workspace changes (4.1s)
|
||||
✓ 37 [chromium] › tests/e2e/operations.spec.js:435:1 › OpenAPI upload only renders the latest selected file and clears reset or close races (3.7s)
|
||||
✓ 38 [chromium] › tests/e2e/operations.spec.js:515:1 › OpenAPI upload ignores a stale failure and renders only correlation identifiers (3.0s)
|
||||
✓ 39 [chromium] › tests/e2e/secrets.spec.js:4:1 › created workspace secret renders styled table actions (2.0s)
|
||||
✓ 40 [chromium] › tests/e2e/secrets.spec.js:30:1 › secret modal shows fields for selected secret kind only (2.1s)
|
||||
✓ 41 [chromium] › tests/e2e/secrets.spec.js:69:1 › generic json secret modal stays inside compact viewport (1.9s)
|
||||
✓ 42 [chromium] › tests/e2e/secrets.spec.js:88:1 › secret modal clears sensitive values and locks duplicate submit while saving (2.0s)
|
||||
✓ 43 [chromium] › tests/e2e/secrets.spec.js:141:1 › stale secret rotation cannot close or report success for a newer modal context (2.8s)
|
||||
✓ 44 [chromium] › tests/e2e/staging-authenticated.spec.js:16:1 › authenticated staging smoke logs in and exposes session json (1.8s)
|
||||
✓ 45 [chromium] › tests/e2e/staging-authenticated.spec.js:25:1 › authenticated staging smoke opens core pages without console errors (4.5s)
|
||||
✓ 46 [chromium] › tests/e2e/wizard.spec.js:23:1 › mobile wizard progress connector crosses the indicator centers (1.8s)
|
||||
✓ 47 [chromium] › tests/e2e/wizard.spec.js:46:1 › onboarding helper does not cover wizard navigation (2.0s)
|
||||
✓ 48 [chromium] › tests/e2e/wizard.spec.js:52:1 › onboarding helper does not cover wizard navigation on mobile (1.8s)
|
||||
✓ 49 [chromium] › tests/e2e/wizard.spec.js:59:1 › wizard loads and protocol selection updates flow (2.4s)
|
||||
✓ 50 [chromium] › tests/e2e/wizard.spec.js:80:1 › community wizard exposes REST-only protocol flow (3.2s)
|
||||
✓ 51 [chromium] › tests/e2e/wizard.spec.js:95:1 › REST method callout clears when switching to methods without request body (3.6s)
|
||||
✓ 52 [chromium] › tests/e2e/wizard.spec.js:152:1 › wizard loads reusable upstreams from backend (2.7s)
|
||||
✓ 53 [chromium] › tests/e2e/wizard.spec.js:191:1 › wizard builds visual request mappings from JSON sample and path params (3.8s)
|
||||
✓ 54 [chromium] › tests/e2e/wizard.spec.js:253:1 › wizard edit mode hydrates fields from operation version snapshot (2.9s)
|
||||
✓ 55 [chromium] › tests/e2e/wizard.spec.js:475:1 › wizard shows agent-facing MCP preview from current draft fields (3.2s)
|
||||
✓ 56 [chromium] › tests/e2e/wizard.spec.js:674:1 › wizard edit mode preserves explicit request mapping targets on save (2.6s)
|
||||
✓ 57 [chromium] › tests/e2e/workspace-settings.spec.js:4:1 › workspace and settings pages show live session data (2.1s)
|
||||
|
||||
57 passed (2.7m)
|
||||
@@ -0,0 +1,91 @@
|
||||
npm notice run e2e
|
||||
npm notice run playwright test --workers=1 --retries=0
|
||||
|
||||
Running 56 tests using 1 worker
|
||||
|
||||
(node:249960) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
|
||||
(Use `node --trace-warnings ...` to show where the warning was created)
|
||||
✓ 1 [chromium] › tests/e2e/agents.spec.js:4:1 › agents page shows demo cards and edit drawer opens (2.4s)
|
||||
✓ 2 [chromium] › tests/e2e/agents.spec.js:28:1 › agent drawer configures on-demand tool discovery and catalog sections (2.6s)
|
||||
✓ 3 [chromium] › tests/e2e/agents.spec.js:51:1 › agent lifecycle stale conflict shows localized recovery message (1.7s)
|
||||
✓ 4 [chromium] › tests/e2e/api-keys.spec.js:4:1 › api keys page opens create key flow (3.1s)
|
||||
✓ 5 [chromium] › tests/e2e/api-keys.spec.js:65:1 › failed clipboard write preserves one-time key material (2.2s) # community-scope: allow=one-time-token
|
||||
✓ 6 [chromium] › tests/e2e/api-keys.spec.js:101:1 › ambiguous create failure reconciles metadata before deliberate retry (2.6s)
|
||||
✓ 7 [chromium] › tests/e2e/api-keys.spec.js:136:1 › stale create response reconciles metadata without changing a newer modal generation (2.8s)
|
||||
✓ 8 [chromium] › tests/e2e/api-keys.spec.js:217:1 › duplicate key revoke and delete clicks send one request while the first request is pending (2.6s)
|
||||
✓ 9 [chromium] › tests/e2e/approvals.spec.js:4:1 › logs approval panel renders safe pending approval metadata (2.2s)
|
||||
✓ 10 [chromium] › tests/e2e/login.spec.js:41:1 › login page rejects invalid credentials (971ms)
|
||||
✓ 11 [chromium] › tests/e2e/login.spec.js:49:1 › login page signs in and redirects to operations (1.1s)
|
||||
✓ 12 [chromium] › tests/e2e/login.spec.js:81:1 › login page switches to bootstrap mode and submits one-time token (1.1s) # community-scope: allow=one-time-token
|
||||
✓ 13 [chromium] › tests/e2e/login.spec.js:107:1 › CrankApi attaches csrf token to unsafe auth requests (519ms)
|
||||
✓ 14 [chromium] › tests/e2e/logs-usage.spec.js:4:1 › logs and usage pages show seeded data (2.4s)
|
||||
✓ 15 [chromium] › tests/e2e/observability.spec.js:4:1 › shell and wizard expose stable diagnostics hooks (2.4s)
|
||||
✓ 16 [chromium] › tests/e2e/observability.spec.js:19:1 › secrets page exposes stable secret management hooks (1.8s)
|
||||
✓ 17 [chromium] › tests/e2e/observability.spec.js:32:1 › API errors retain only bounded canonical support identities (1.4s)
|
||||
✓ 18 [chromium] › tests/e2e/onboarding.spec.js:70:1 › optional Getting Started checklist is server-derived, resumable, bilingual and accessible (3.8s)
|
||||
✓ 19 [chromium] › tests/e2e/onboarding.spec.js:136:1 › onboarding error exposes safe support correlation and retries without a client completion bypass (2.1s)
|
||||
✓ 20 [chromium] › tests/e2e/onboarding.spec.js:176:1 › validation, upstream and compatibility errors recover from the last authoritative onboarding step (2.6s)
|
||||
✓ 21 [chromium] › tests/e2e/onboarding.spec.js:222:1 › authentication recovery returns to an incomplete authoritative onboarding projection (3.0s)
|
||||
✓ 22 [chromium] › tests/e2e/onboarding.spec.js:250:1 › a BroadcastChannel refresh updates a second open tab from server progress (2.7s)
|
||||
✓ 23 [chromium] › tests/e2e/onboarding.spec.js:276:1 › bursty browser refresh signals coalesce into one request plus one trailing refresh (1.8s)
|
||||
✓ 24 [chromium] › tests/e2e/onboarding.spec.js:336:1 › stale onboarding deep link requires server reset before explicit reselection (2.5s)
|
||||
✓ 25 [chromium] › tests/e2e/onboarding.spec.js:371:1 › one-time key connection config is never recoverable after the reveal is lost (2.9s) # community-scope: allow=one-time-token
|
||||
✓ 26 [chromium] › tests/e2e/onboarding.spec.js:410:1 › first value is proven only by a real tools/call through the public MCP endpoint (11.0s)
|
||||
✘ 27 [chromium] › tests/e2e/operation-lifecycle.spec.js:4:1 › Operation lifecycle keeps published versions immutable and exposes safe correlation (1.5s)
|
||||
(node:250896) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
|
||||
(Use `node --trace-warnings ...` to show where the warning was created)
|
||||
✓ 28 [chromium] › tests/e2e/operation-lifecycle.spec.js:132:3 › catalog lifecycle actions are state-aware in ru (3.7s)
|
||||
✓ 29 [chromium] › tests/e2e/operation-lifecycle.spec.js:132:3 › catalog lifecycle actions are state-aware in en (3.3s)
|
||||
✓ 30 [chromium] › tests/e2e/operations.spec.js:14:1 › operations page shows demo catalog and filter works (1.7s)
|
||||
✓ 31 [chromium] › tests/e2e/operations.spec.js:26:1 › operations page imports OpenAPI methods as drafts (3.2s)
|
||||
✓ 32 [chromium] › tests/e2e/operations.spec.js:144:1 › OpenAPI upload rejects invalid files locally and restores focus after Escape (2.9s)
|
||||
✓ 33 [chromium] › tests/e2e/operations.spec.js:210:1 › OpenAPI upload recovers from pagehide and a preview server error (2.3s)
|
||||
✓ 34 [chromium] › tests/e2e/operations.spec.js:245:1 › OpenAPI apply cancellation preserves the import job for an idempotent retry (5.1s)
|
||||
✓ 35 [chromium] › tests/e2e/operations.spec.js:344:1 › OpenAPI apply preserves job authority after language or workspace changes (3.9s)
|
||||
✓ 36 [chromium] › tests/e2e/operations.spec.js:435:1 › OpenAPI upload only renders the latest selected file and clears reset or close races (3.5s)
|
||||
✓ 37 [chromium] › tests/e2e/operations.spec.js:515:1 › OpenAPI upload ignores a stale failure and renders only correlation identifiers (3.2s)
|
||||
✓ 38 [chromium] › tests/e2e/secrets.spec.js:4:1 › created workspace secret renders styled table actions (1.8s)
|
||||
✓ 39 [chromium] › tests/e2e/secrets.spec.js:30:1 › secret modal shows fields for selected secret kind only (1.9s)
|
||||
✓ 40 [chromium] › tests/e2e/secrets.spec.js:69:1 › generic json secret modal stays inside compact viewport (1.7s)
|
||||
✓ 41 [chromium] › tests/e2e/secrets.spec.js:88:1 › secret modal clears sensitive values and locks duplicate submit while saving (2.0s)
|
||||
✓ 42 [chromium] › tests/e2e/secrets.spec.js:141:1 › stale secret rotation cannot close or report success for a newer modal context (2.4s)
|
||||
✓ 43 [chromium] › tests/e2e/staging-authenticated.spec.js:16:1 › authenticated staging smoke logs in and exposes session json (1.5s)
|
||||
✓ 44 [chromium] › tests/e2e/staging-authenticated.spec.js:25:1 › authenticated staging smoke opens core pages without console errors (4.4s)
|
||||
✓ 45 [chromium] › tests/e2e/wizard.spec.js:23:1 › mobile wizard progress connector crosses the indicator centers (1.7s)
|
||||
✓ 46 [chromium] › tests/e2e/wizard.spec.js:46:1 › onboarding helper does not cover wizard navigation (1.8s)
|
||||
✓ 47 [chromium] › tests/e2e/wizard.spec.js:52:1 › onboarding helper does not cover wizard navigation on mobile (1.4s)
|
||||
✓ 48 [chromium] › tests/e2e/wizard.spec.js:59:1 › wizard loads and protocol selection updates flow (2.1s)
|
||||
✓ 49 [chromium] › tests/e2e/wizard.spec.js:80:1 › community wizard exposes REST-only protocol flow (2.7s)
|
||||
✓ 50 [chromium] › tests/e2e/wizard.spec.js:95:1 › REST method callout clears when switching to methods without request body (3.5s)
|
||||
✓ 51 [chromium] › tests/e2e/wizard.spec.js:152:1 › wizard loads reusable upstreams from backend (2.4s)
|
||||
✓ 52 [chromium] › tests/e2e/wizard.spec.js:191:1 › wizard builds visual request mappings from JSON sample and path params (4.3s)
|
||||
✓ 53 [chromium] › tests/e2e/wizard.spec.js:253:1 › wizard edit mode hydrates fields from operation version snapshot (3.0s)
|
||||
✓ 54 [chromium] › tests/e2e/wizard.spec.js:475:1 › wizard shows agent-facing MCP preview from current draft fields (3.3s)
|
||||
✓ 55 [chromium] › tests/e2e/wizard.spec.js:674:1 › wizard edit mode preserves explicit request mapping targets on save (2.7s)
|
||||
✓ 56 [chromium] › tests/e2e/workspace-settings.spec.js:4:1 › workspace and settings pages show live session data (2.0s)
|
||||
|
||||
|
||||
1) [chromium] › tests/e2e/operation-lifecycle.spec.js:4:1 › Operation lifecycle keeps published versions immutable and exposes safe correlation
|
||||
|
||||
Error: page.evaluate: Error: csrf validation failed
|
||||
at f (http://127.0.0.1:3300/js/bundles/protected-core.70fc1c2160cb.js:3:70752)
|
||||
at async eval (eval at evaluate (:303:30), <anonymous>:60:21)
|
||||
at async <anonymous>:329:30
|
||||
at f (http://127.0.0.1:3300/js/bundles/protected-core.70fc1c2160cb.js:3:70752)
|
||||
at async eval (eval at evaluate (:303:30), <anonymous>:60:21)
|
||||
at async <anonymous>:329:30
|
||||
at <checkout>/apps/ui/tests/e2e/operation-lifecycle.spec.js:9:31
|
||||
|
||||
attachment #1: screenshot (image/png) ──────────────────────────────────────────────────────────
|
||||
test-results/operation-lifecycle-Operat-51fc7-nd-exposes-safe-correlation-chromium/test-failed-1.png
|
||||
────────────────────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
attachment #2: video (video/webm) ──────────────────────────────────────────────────────────────
|
||||
test-results/operation-lifecycle-Operat-51fc7-nd-exposes-safe-correlation-chromium/video.webm
|
||||
────────────────────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
Error Context: test-results/operation-lifecycle-Operat-51fc7-nd-exposes-safe-correlation-chromium/error-context.md
|
||||
|
||||
1 failed
|
||||
[chromium] › tests/e2e/operation-lifecycle.spec.js:4:1 › Operation lifecycle keeps published versions immutable and exposes safe correlation
|
||||
55 passed (2.5m)
|
||||
@@ -0,0 +1,45 @@
|
||||
npm notice run e2e
|
||||
npm notice run playwright test tests/e2e/onboarding.spec.js --grep validation, upstream and compatibility --workers=1 --retries=0
|
||||
|
||||
Running 1 test using 1 worker
|
||||
|
||||
(node:247608) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
|
||||
(Use `node --trace-warnings ...` to show where the warning was created)
|
||||
✘ 1 [chromium] › tests/e2e/onboarding.spec.js:176:1 › validation, upstream and compatibility errors recover from the last authoritative onboarding step (13.8s)
|
||||
|
||||
|
||||
1) [chromium] › tests/e2e/onboarding.spec.js:176:1 › validation, upstream and compatibility errors recover from the last authoritative onboarding step
|
||||
|
||||
Error: expect(locator).toContainText(expected) failed
|
||||
|
||||
Locator: getByRole('alert')
|
||||
Expected substring: "onboarding_validation_failed"
|
||||
Timeout: 10000ms
|
||||
Error: element(s) not found
|
||||
|
||||
Call log:
|
||||
- Expect "toContainText" with timeout 10000ms
|
||||
- waiting for getByRole('alert')
|
||||
|
||||
|
||||
207 | await page.getByTestId('onboarding-refresh').click();
|
||||
208 | const alert = page.getByRole('alert');
|
||||
> 209 | await expect(alert).toContainText(failures[index].code);
|
||||
| ^
|
||||
210 | await expect(alert).toContainText(`req_onboarding_${failures[index].status}`);
|
||||
211 | await expect(alert).toContainText('0123456789abcdef0123456789abcdef');
|
||||
212 | await page.getByTestId('onboarding-retry').click();
|
||||
at <checkout>/apps/ui/tests/e2e/onboarding.spec.js:209:25
|
||||
|
||||
attachment #1: screenshot (image/png) ──────────────────────────────────────────────────────────
|
||||
test-results/onboarding-validation-upst-1c5f1-thoritative-onboarding-step-chromium/test-failed-1.png
|
||||
────────────────────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
attachment #2: video (video/webm) ──────────────────────────────────────────────────────────────
|
||||
test-results/onboarding-validation-upst-1c5f1-thoritative-onboarding-step-chromium/video.webm
|
||||
────────────────────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
Error Context: test-results/onboarding-validation-upst-1c5f1-thoritative-onboarding-step-chromium/error-context.md
|
||||
|
||||
1 failed
|
||||
[chromium] › tests/e2e/onboarding.spec.js:176:1 › validation, upstream and compatibility errors recover from the last authoritative onboarding step
|
||||
@@ -0,0 +1,47 @@
|
||||
npm notice run e2e
|
||||
npm notice run playwright test tests/e2e/operations.spec.js --grep imports OpenAPI methods as drafts --workers=1 --retries=0
|
||||
|
||||
Running 1 test using 1 worker
|
||||
|
||||
(node:246848) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
|
||||
(Use `node --trace-warnings ...` to show where the warning was created)
|
||||
✘ 1 [chromium] › tests/e2e/operations.spec.js:26:1 › operations page imports OpenAPI methods as drafts (14.2s)
|
||||
|
||||
|
||||
1) [chromium] › tests/e2e/operations.spec.js:26:1 › operations page imports OpenAPI methods as drafts
|
||||
|
||||
Error: expect(locator).toContainText(expected) failed
|
||||
|
||||
Locator: locator('.openapi-import-operation').filter({ hasText: 'Получить курсы валют' }).locator('.openapi-import-mapping-preview')
|
||||
Expected substring: "symbols"
|
||||
Received string: "PathdateQuerybaseHeaderX-API-VersionBodybodyResponsebase ← base"
|
||||
Timeout: 10000ms
|
||||
|
||||
Call log:
|
||||
- Expect "toContainText" with timeout 10000ms
|
||||
- waiting for locator('.openapi-import-operation').filter({ hasText: 'Получить курсы валют' }).locator('.openapi-import-mapping-preview')
|
||||
23 × locator resolved to <div class="openapi-import-mapping-preview">…</div>
|
||||
- unexpected value "PathdateQuerybaseHeaderX-API-VersionBodybodyResponsebase ← base"
|
||||
|
||||
|
||||
113 | await expect(importedOperation.locator('.openapi-import-mapping-preview')).toContainText('X-API-Version');
|
||||
114 | await expect(importedOperation.locator('.openapi-import-mapping-preview')).toContainText('Body');
|
||||
> 115 | await expect(importedOperation.locator('.openapi-import-mapping-preview')).toContainText('symbols');
|
||||
| ^
|
||||
116 | await expect(importedOperation.locator('.openapi-import-mapping-preview')).toContainText(localized('Response', 'Ответ'));
|
||||
117 | await expect(page.locator('#openapi-import-selection')).toContainText(localized('Selected: 2', 'Выбрано: 2'));
|
||||
118 | await page.locator('#openapi-import-search').fill('status');
|
||||
at <checkout>/apps/ui/tests/e2e/operations.spec.js:115:78
|
||||
|
||||
attachment #1: screenshot (image/png) ──────────────────────────────────────────────────────────
|
||||
test-results/operations-operations-page-imports-OpenAPI-methods-as-drafts-chromium/test-failed-1.png
|
||||
────────────────────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
attachment #2: video (video/webm) ──────────────────────────────────────────────────────────────
|
||||
test-results/operations-operations-page-imports-OpenAPI-methods-as-drafts-chromium/video.webm
|
||||
────────────────────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
Error Context: test-results/operations-operations-page-imports-OpenAPI-methods-as-drafts-chromium/error-context.md
|
||||
|
||||
1 failed
|
||||
[chromium] › tests/e2e/operations.spec.js:26:1 › operations page imports OpenAPI methods as drafts
|
||||
@@ -0,0 +1,8 @@
|
||||
|
||||
Running 1 test using 1 worker
|
||||
|
||||
(node:259440) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
|
||||
(Use `node --trace-warnings ...` to show where the warning was created)
|
||||
✓ 1 ../../../crank-epic1-pr-20261004-state/login-ready-harness/login-ready.spec.js:7:1 › login helper leaves a ready CSRF session under a delayed csrf refresh (2.0s)
|
||||
|
||||
1 passed (3.2s)
|
||||
@@ -0,0 +1,32 @@
|
||||
|
||||
Running 1 test using 1 worker
|
||||
|
||||
(node:257457) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
|
||||
(Use `node --trace-warnings ...` to show where the warning was created)
|
||||
✘ 1 ../../../crank-epic1-pr-20261004-state/login-ready-harness/login-ready.spec.js:7:1 › login helper leaves a ready CSRF session under a delayed csrf refresh (1.5s)
|
||||
|
||||
|
||||
1) ../../../crank-epic1-pr-20261004-state/login-ready-harness/login-ready.spec.js:7:1 › login helper leaves a ready CSRF session under a delayed csrf refresh
|
||||
|
||||
Error: expect(received).toBe(expected) // Object.is equality
|
||||
|
||||
Expected: true
|
||||
Received: false
|
||||
|
||||
18 | () => Boolean(window.CrankAuth && typeof window.CrankAuth.getCsrfToken === 'function' && window.CrankAuth.getCsrfToken())
|
||||
19 | );
|
||||
> 20 | expect(tokenReady).toBe(true);
|
||||
| ^
|
||||
21 | expect(csrfRequests).toBeGreaterThan(0);
|
||||
22 | });
|
||||
23 |
|
||||
at <evidence-state>/login-ready-harness/login-ready.spec.js:20:22
|
||||
|
||||
attachment #1: screenshot (image/png) ──────────────────────────────────────────────────────────
|
||||
test-results/login-ready-login-helper-l-56b6f-nder-a-delayed-csrf-refresh/test-failed-1.png
|
||||
────────────────────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
Error Context: test-results/login-ready-login-helper-l-56b6f-nder-a-delayed-csrf-refresh/error-context.md
|
||||
|
||||
1 failed
|
||||
../../../crank-epic1-pr-20261004-state/login-ready-harness/login-ready.spec.js:7:1 › login helper leaves a ready CSRF session under a delayed csrf refresh
|
||||
@@ -0,0 +1 @@
|
||||
{"before_draft":1,"after_draft":2,"saved_version":2,"published_unchanged":true,"error":null}
|
||||
@@ -0,0 +1,24 @@
|
||||
npm notice run e2e
|
||||
npm notice run playwright test tests/e2e/onboarding.spec.js tests/e2e/operation-lifecycle.spec.js tests/e2e/agents.spec.js --workers=1 --retries=0
|
||||
|
||||
Running 15 tests using 1 worker
|
||||
|
||||
(node:228979) Warning: The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.
|
||||
(Use `node --trace-warnings ...` to show where the warning was created)
|
||||
✓ 1 [chromium] › tests/e2e/agents.spec.js:4:1 › agents page shows demo cards and edit drawer opens (4.3s)
|
||||
✓ 2 [chromium] › tests/e2e/agents.spec.js:28:1 › agent drawer configures on-demand tool discovery and catalog sections (4.1s)
|
||||
✓ 3 [chromium] › tests/e2e/agents.spec.js:51:1 › agent lifecycle stale conflict shows localized recovery message (2.8s)
|
||||
✓ 4 [chromium] › tests/e2e/onboarding.spec.js:70:1 › optional Getting Started checklist is server-derived, resumable, bilingual and accessible (4.7s)
|
||||
✓ 5 [chromium] › tests/e2e/onboarding.spec.js:136:1 › onboarding error exposes safe support correlation and retries without a client completion bypass (2.9s)
|
||||
✓ 6 [chromium] › tests/e2e/onboarding.spec.js:176:1 › validation, upstream and compatibility errors recover from the last authoritative onboarding step (3.1s)
|
||||
✓ 7 [chromium] › tests/e2e/onboarding.spec.js:219:1 › authentication recovery returns to an incomplete authoritative onboarding projection (3.7s)
|
||||
✓ 8 [chromium] › tests/e2e/onboarding.spec.js:247:1 › a BroadcastChannel refresh updates a second open tab from server progress (3.5s)
|
||||
✓ 9 [chromium] › tests/e2e/onboarding.spec.js:273:1 › bursty browser refresh signals coalesce into one request plus one trailing refresh (2.6s)
|
||||
✓ 10 [chromium] › tests/e2e/onboarding.spec.js:333:1 › stale onboarding deep link requires server reset before explicit reselection (3.5s)
|
||||
✓ 11 [chromium] › tests/e2e/onboarding.spec.js:368:1 › one-time key connection config is never recoverable after the reveal is lost (3.9s) # community-scope: allow=one-time-token
|
||||
✓ 12 [chromium] › tests/e2e/onboarding.spec.js:407:1 › first value is proven only by a real tools/call through the public MCP endpoint (16.1s)
|
||||
✓ 13 [chromium] › tests/e2e/operation-lifecycle.spec.js:4:1 › Operation lifecycle keeps published versions immutable and exposes safe correlation (5.7s)
|
||||
✓ 14 [chromium] › tests/e2e/operation-lifecycle.spec.js:132:3 › catalog lifecycle actions are state-aware in ru (5.9s)
|
||||
✓ 15 [chromium] › tests/e2e/operation-lifecycle.spec.js:132:3 › catalog lifecycle actions are state-aware in en (5.3s)
|
||||
|
||||
15 passed (1.3m)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,2 @@
|
||||
Running 17 tests using 1 worker
|
||||
17 passed (58.6s)
|
||||
@@ -0,0 +1,31 @@
|
||||
Running 17 tests using 1 worker
|
||||
::error file=tests/e2e/onboarding.spec.js,title=[chromium] › tests/e2e/onboarding.spec.js:189:1 › onboarding error exposes safe support correlation and retries without a client completion bypass,line=215,col=48:: 1) [chromium] › tests/e2e/onboarding.spec.js:189:1 › onboarding error exposes safe support correlation and retries without a client completion bypass
|
||||
Error: locator.click: Test timeout of 45000ms exceeded.
|
||||
Call log:
|
||||
- waiting for getByTestId('onboarding-refresh')
|
||||
- locator resolved to <button type="button" class="onboarding-link-button" data-testid="onboarding-refresh">Refresh progress</button>
|
||||
- attempting click action
|
||||
2 × waiting for element to be visible, enabled and stable
|
||||
- element is not visible
|
||||
- retrying click action
|
||||
- waiting 20ms
|
||||
2 × waiting for element to be visible, enabled and stable
|
||||
- element is not visible
|
||||
- retrying click action
|
||||
- waiting 100ms
|
||||
101 × waiting for element to be visible, enabled and stable
|
||||
- element is not visible
|
||||
- retrying click action
|
||||
- waiting 500ms
|
||||
|
||||
|
||||
213 | await page.getByTestId('onboarding-trigger').click();
|
||||
214 | fail = true;
|
||||
> 215 | await page.getByTestId('onboarding-refresh').click();
|
||||
| ^
|
||||
216 | const alert = page.getByRole('alert');
|
||||
217 | await expect(alert).toContainText('onboarding_unavailable');
|
||||
218 | await expect(alert).toContainText('req_onboarding_retry');
|
||||
at apps/ui/tests/e2e/onboarding.spec.js:215:48
|
||||
1 flaky
|
||||
16 passed (2.5m)
|
||||
@@ -0,0 +1,43 @@
|
||||
# Итоговое ревью исправлений Epic 1
|
||||
|
||||
Три независимых reviewer layer завершены: blind hunter, edge cases, verification gaps. Verification-gap layer: `No verification gaps found.` Каждый finding оценён отдельно до группировки. Blind hunter ошибочно вычислил floor без min(..., 10); все 30 выданных findings всё равно рассмотрены.
|
||||
|
||||
| ID | Verdict | Route | Evidence / решение |
|
||||
|---|---|---|---|
|
||||
| B01 | medium | patch | Ссылка sqlx-red.patch ещё не разрешается; exact patch сохранён вне репозитория и включается в completion evidence. |
|
||||
| B02 | medium | patch | Ссылка sqlx-accepted.patch ещё не разрешается; принятый exact patch сохранён и включается в completion evidence. |
|
||||
| B03 | medium | patch | В Git пока лишь excerpts SQLx; добавляются sanitized RED и clean GREEN summaries, raw-log SHA и commands/exit. Raw logs не публикуются целиком согласно evidence policy. |
|
||||
| B04 | medium | patch | Digest metadata пока вне Git; source archive/intermediate hashes и artifact hashes добавляются в index. |
|
||||
| B05 | medium | patch | Versioned completion index на момент review ещё собирается; добавляется после реального gate и final UI. |
|
||||
| B06 | medium | patch | Run records пока вне Git; итоговый index добавляет source/config revisions, environment, command, exit, counts и digests. |
|
||||
| B07 | false | reject | 100755 сохранён из crates.io archive, исполняемый бит не влияет на cargo compilation. Нормализация vendor modes создаст ненужный provenance diff; ordinary harm не показан. |
|
||||
| B08 | false | reject | Canonical Rust workspace задаётся apps/* и crates/*; в корневых tests только Python tooling, корневых Rust benches/examples нет. Vendor — отдельный upstream package. Потеря текущего source gate не показана. |
|
||||
| B09 | false | reject | Предположенный root Rust source отсутствует в workspace; scanner tests проверяют реально принятые apps/crates и untracked source. Тест несуществующей области не нужен. |
|
||||
| B10 | false | reject | Probe применяется только к ephemeral playwright-stack; teardown удаляет crank-e2e-postgres вместе со всеми synthetic Agents. Описанного накопления при установленном способе запуска нет. |
|
||||
| B11 | false | reject | Stack teardown выполняется также при failed probe через finally у runner. Probe browser.close также finally; записи уходят с fixture DB. |
|
||||
| B12 | false | reject | Документ явно требует default-port stack. Эта диагностическая проверка не обещает произвольную deployment configuration; недоступный адрес завершает её ошибкой. |
|
||||
| B13 | false | reject | Это открытые synthetic fixture credentials из playwright-stack.sh, не секреты. User-facing login проверяется на стандартной fixture конфигурации. |
|
||||
| B14 | false | reject | Свежий stack имеет опубликованный fixture Agent; копируются exact published Operation references, имени source Agent в oracle нет. Любой такой Agent подходит для проверки собственного fork. |
|
||||
| B15 | false | reject | Fixtures на свежем stack содержат Published bindings; полный Rust regression независимо утверждает nonempty bindings и фактический title в Draft. Пустая fixture здесь не наблюдается. |
|
||||
| B16 | low | reject | Ошибка версии прервёт probe при version.bindings.map, PASS не получится. Улучшение диагностики редкого отсутствующего fixture потребовало бы дополнительного guard; correctness defect отсутствует. |
|
||||
| B17 | false | reject | Оба Published reads сериализуются одним API/serde и JSONB; в данном snapshot порядок стабилен. Counterexample перестановки ключей на этом пути отсутствует. |
|
||||
| B18 | false | reject | Oracle mode/max_results и сохранённые bindings закрепляют atomic fork/save; groups persistence использует ту же целиком сериализованную policy, дополнительные group search проверены operations_agents. Поведенческий дефект не показан. |
|
||||
| B19 | false | reject | First response version=2, summary current_draft=2, version_count=2 и Published immutable закреплены. Второй edit проверяет успешность и отсутствие новой версии; возврат неправильной версии не показан. |
|
||||
| B20 | false | reject | Сохранение binding title непосредственно проверено при первом edit; существующий Draft использует прежний strict transaction/save путь. Дополнительный identical assertion не закрывает найденный дефект. |
|
||||
| B21 | false | reject | Race oracle требует ровно один success, один stable agent_stale_revision conflict, ровно один Draft и Published unchanged. Общий save oracle проверяет contents отдельно; гипотетическая подмена winning payload не установлена. |
|
||||
| B22 | false | reject | SQL text используется лишь для наблюдения именно нужного lock waiter вместе с независимым holder PID и pg_blocking_pids. Изменение lock protocol должно требовать обновления fixture; ложное зелёное ожидание исключено. |
|
||||
| B23 | false | reject | Archive-race AC — rejection without durable mutation; точный validation error vs serialized archive conflict зависит от победителя. Любой client rejection допустим при отдельном unchanged oracle. |
|
||||
| B24 | false | reject | Pre-archived rejection проверяет client error и exact unchanged Agent/versions. Retrospective finding касается durable fork на rejected references, не нового error-code контракта. |
|
||||
| B25 | false | reject | Browser probe передаёт legacy bindings array без tool_selection_policy на первом fork; default-preserving production branch unchanged, выбирается из Published current snapshot. No-policy путь не отсутствует. |
|
||||
| B26 | false | reject | Concurrent losing original ETag проходит после winning fork и проверяет именно agent_stale_revision, то есть stale state current Draft=2 vs expected=1. Та же locked CAS не зависит от одновременности arrival. |
|
||||
| B27 | false | reject | Runtime matrix покрывает 429, core test removes retry_after_ms; Admin/MCP parity проецирует все affected codes, live POST503 доказывает transport→history без retry. Отдельный live429 — дублирование слоёв, не непроверенный branch. |
|
||||
| B28 | false | reject | 408 покрыт runtime method/dispatch/status matrix и common normalization/projection. Live503 покрывает тот же status→uncertainty seam; уникального HTTP408 branch не показано. |
|
||||
| B29 | false | reject | ResponseTooLarge включён behavioral runtime matrix вместе с invalid response, не только core normalization. Общая Admin/MCP projection проверена, adapter dispatch evidence существовало до изменения. |
|
||||
| B30 | false | reject | Документ уже требует verified upstream fix перед удалением patch и rebase при upgrade; конкретного upstream issue пока нет. Создавать фиктивную ссылку или новую ownership abstraction не требуется. |
|
||||
| E01 | low | reject | Overflow i32 действительно возможен после 2147483647 Published versions, но тот же unchecked +1/to_db_version существовал до изменения в ensure_editable_agent_version. В ordinary lifecycle недостижимо; новый guard/branch больше прямой коррекции, по правилам low rejected. |
|
||||
| E02 | false | reject | Probe fixture очищается при finally teardown всего ephemeral stack и его контейнера/БД; накопление записей в поддерживаемом запуске не происходит. |
|
||||
| E03 | medium | patch | Completion evidence на момент review ещё собирается; claim закрывается versioned index и проверкой links/digests после current gate. |
|
||||
|
||||
B01–B06/E03 имеют общий root cause: versioned completion bundle ещё не сохранён во время review; исправление — итоговый index и immutable summaries/patches. Продуктовые изменения дополнительного patch не требуют. Deferred entries не добавлены. Minor upstream integer limit сохранён как limitation исходного lifecycle, не новый defect Epic 1.
|
||||
|
||||
После review обнаружен flaky в исходном onboarding E2E test: unconditional toggle закрывал уже auto-opened checklist. Минимальное изменение использует соседний conditional pattern и visible assertion; ведущий проверил state.open/performRefresh и diff. Targeted 3 повторения без retries зелёные; final 17 cases также без retries. Rust source/tests/scripts/Cargo совпадают с полной проверенной ревизией. Первоначальный flaky запуск сохранён отдельной записью. B01–B06/E03 закрыты сохранённым index и integrity validation.
|
||||
@@ -0,0 +1,250 @@
|
||||
diff --git a/crates/crank-runtime/tests/execution_certainty.rs b/crates/crank-runtime/tests/execution_certainty.rs
|
||||
new file mode 100644
|
||||
index 0000000..9c8a4a6
|
||||
--- /dev/null
|
||||
+++ b/crates/crank-runtime/tests/execution_certainty.rs
|
||||
@@ -0,0 +1,244 @@
|
||||
+use std::collections::BTreeMap;
|
||||
+
|
||||
+use crank_core::{
|
||||
+ CorrelationContext, DispatchEvidence, ExecutionErrorCode, ExecutionFailure, HttpMethod,
|
||||
+ OutcomeCertainty, Protocol, ProtocolAdapterError, RestTarget, Retryability, Target,
|
||||
+ ToolDescription,
|
||||
+};
|
||||
+use crank_mapping::MappingSet;
|
||||
+use crank_runtime::{RuntimeError, RuntimeOperation, normalize_runtime_error_for_operation};
|
||||
+use crank_schema::{Schema, SchemaKind};
|
||||
+
|
||||
+const MUTATING_METHODS: [HttpMethod; 4] = [
|
||||
+ HttpMethod::Post,
|
||||
+ HttpMethod::Put,
|
||||
+ HttpMethod::Patch,
|
||||
+ HttpMethod::Delete,
|
||||
+];
|
||||
+const READ_METHODS: [HttpMethod; 2] = [HttpMethod::Get, HttpMethod::Head];
|
||||
+const UNCERTAIN_STATUSES: [u16; 4] = [408, 429, 500, 503];
|
||||
+
|
||||
+#[test]
|
||||
+fn ambiguous_upstream_failures_are_unknown_only_for_dispatched_mutations() {
|
||||
+ let mut failures = Vec::new();
|
||||
+ for method in MUTATING_METHODS.into_iter().chain(READ_METHODS) {
|
||||
+ for dispatch in [
|
||||
+ DispatchEvidence::MayHaveDispatched,
|
||||
+ DispatchEvidence::NotDispatched,
|
||||
+ ] {
|
||||
+ for status in UNCERTAIN_STATUSES {
|
||||
+ let error = RuntimeError::ProtocolAdapter(ProtocolAdapterError::UnexpectedStatus {
|
||||
+ status,
|
||||
+ dispatch,
|
||||
+ });
|
||||
+ if let Err(failure) = assert_normalization(
|
||||
+ method,
|
||||
+ &error,
|
||||
+ is_ambiguous_mutation(method, dispatch),
|
||||
+ Some(status),
|
||||
+ format!("{method:?} status {status} {dispatch:?}"),
|
||||
+ ) {
|
||||
+ failures.push(failure);
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ for adapter in [
|
||||
+ ProtocolAdapterError::ResponseTooLarge { dispatch },
|
||||
+ ProtocolAdapterError::InvalidResponse { dispatch },
|
||||
+ ] {
|
||||
+ let error = RuntimeError::ProtocolAdapter(adapter);
|
||||
+ if let Err(failure) = assert_normalization(
|
||||
+ method,
|
||||
+ &error,
|
||||
+ is_ambiguous_mutation(method, dispatch),
|
||||
+ None,
|
||||
+ format!("{method:?} {error:?}"),
|
||||
+ ) {
|
||||
+ failures.push(failure);
|
||||
+ }
|
||||
+ }
|
||||
+ }
|
||||
+ }
|
||||
+ assert!(
|
||||
+ failures.is_empty(),
|
||||
+ "unexpected normalization rows:\n{}",
|
||||
+ failures.join("\n")
|
||||
+ );
|
||||
+}
|
||||
+
|
||||
+#[test]
|
||||
+fn nonambiguous_statuses_keep_their_existing_descriptor() {
|
||||
+ let mut failures = Vec::new();
|
||||
+ for method in MUTATING_METHODS.into_iter().chain(READ_METHODS) {
|
||||
+ for status in [401, 404] {
|
||||
+ let error = RuntimeError::ProtocolAdapter(ProtocolAdapterError::UnexpectedStatus {
|
||||
+ status,
|
||||
+ dispatch: DispatchEvidence::MayHaveDispatched,
|
||||
+ });
|
||||
+ if let Err(failure) = assert_normalization(
|
||||
+ method,
|
||||
+ &error,
|
||||
+ false,
|
||||
+ Some(status),
|
||||
+ format!("{method:?} nonambiguous status {status}"),
|
||||
+ ) {
|
||||
+ failures.push(failure);
|
||||
+ }
|
||||
+ }
|
||||
+ }
|
||||
+ assert!(
|
||||
+ failures.is_empty(),
|
||||
+ "unexpected normalization rows:\n{}",
|
||||
+ failures.join("\n")
|
||||
+ );
|
||||
+}
|
||||
+
|
||||
+#[test]
|
||||
+fn dispatch_uncertainty_allowlist_covers_uncertain_upstream_codes_and_drops_retry_delay() {
|
||||
+ let uncertain_codes = [
|
||||
+ ExecutionErrorCode::UpstreamRateLimited,
|
||||
+ ExecutionErrorCode::UpstreamServerError,
|
||||
+ ExecutionErrorCode::UpstreamResponseTooLarge,
|
||||
+ ExecutionErrorCode::UpstreamStatusError,
|
||||
+ ];
|
||||
+ let mut failures = Vec::new();
|
||||
+ for code in uncertain_codes {
|
||||
+ let failure = ExecutionFailure::new(code, CorrelationContext::generate());
|
||||
+ let failure = if matches!(code.retryability(), Retryability::AfterDelay) {
|
||||
+ failure
|
||||
+ .try_with_retry_after_ms(1_000)
|
||||
+ .expect("retry delay is valid for the original descriptor")
|
||||
+ } else {
|
||||
+ failure
|
||||
+ }
|
||||
+ .with_dispatch_uncertainty();
|
||||
+
|
||||
+ if failure.error_code() != code
|
||||
+ || failure.retryability() != Retryability::ManualReconcile
|
||||
+ || failure.outcome_certainty() != OutcomeCertainty::OutcomeUnknown
|
||||
+ || failure.retry_after_ms().is_some()
|
||||
+ {
|
||||
+ failures.push(format!(
|
||||
+ "{code:?}: actual code={:?}, retryability={:?}, certainty={:?}, retry_after_ms={:?}",
|
||||
+ failure.error_code(),
|
||||
+ failure.retryability(),
|
||||
+ failure.outcome_certainty(),
|
||||
+ failure.retry_after_ms(),
|
||||
+ ));
|
||||
+ }
|
||||
+ }
|
||||
+ assert!(
|
||||
+ failures.is_empty(),
|
||||
+ "uncertain code allowlist failures:\n{}",
|
||||
+ failures.join("\n")
|
||||
+ );
|
||||
+}
|
||||
+
|
||||
+fn assert_normalization(
|
||||
+ method: HttpMethod,
|
||||
+ error: &RuntimeError,
|
||||
+ unknown: bool,
|
||||
+ status: Option<u16>,
|
||||
+ context: String,
|
||||
+) -> Result<(), String> {
|
||||
+ let correlation = CorrelationContext::generate();
|
||||
+ let failure = normalize_runtime_error_for_operation(error, &correlation, &operation(method));
|
||||
+ let code = expected_code(error);
|
||||
+ let expected = ExecutionFailure::new(code, correlation.clone());
|
||||
+ let expected_retryability = if unknown {
|
||||
+ Retryability::ManualReconcile
|
||||
+ } else {
|
||||
+ expected.retryability()
|
||||
+ };
|
||||
+ let expected_certainty = if unknown {
|
||||
+ OutcomeCertainty::OutcomeUnknown
|
||||
+ } else {
|
||||
+ expected.outcome_certainty()
|
||||
+ };
|
||||
+
|
||||
+ if failure.error_code() != code
|
||||
+ || failure.retryability() != expected_retryability
|
||||
+ || failure.outcome_certainty() != expected_certainty
|
||||
+ || failure.upstream_status() != status
|
||||
+ || failure.retry_after_ms().is_some()
|
||||
+ {
|
||||
+ return Err(format!(
|
||||
+ "{context}: code={:?} (expected {code:?}), retryability={:?} (expected {expected_retryability:?}), certainty={:?} (expected {expected_certainty:?}), upstream_status={:?} (expected {status:?}), retry_after_ms={:?}",
|
||||
+ failure.error_code(),
|
||||
+ failure.retryability(),
|
||||
+ failure.outcome_certainty(),
|
||||
+ failure.upstream_status(),
|
||||
+ failure.retry_after_ms(),
|
||||
+ ));
|
||||
+ }
|
||||
+ Ok(())
|
||||
+}
|
||||
+
|
||||
+fn expected_code(error: &RuntimeError) -> ExecutionErrorCode {
|
||||
+ match error {
|
||||
+ RuntimeError::ProtocolAdapter(ProtocolAdapterError::UnexpectedStatus {
|
||||
+ status, ..
|
||||
+ }) => match status {
|
||||
+ 401 | 403 => ExecutionErrorCode::UpstreamAuthError,
|
||||
+ 404 => ExecutionErrorCode::UpstreamNotFound,
|
||||
+ 408 | 429 => ExecutionErrorCode::UpstreamRateLimited,
|
||||
+ 500..=599 => ExecutionErrorCode::UpstreamServerError,
|
||||
+ _ => ExecutionErrorCode::UpstreamStatusError,
|
||||
+ },
|
||||
+ RuntimeError::ProtocolAdapter(ProtocolAdapterError::ResponseTooLarge { .. }) => {
|
||||
+ ExecutionErrorCode::UpstreamResponseTooLarge
|
||||
+ }
|
||||
+ RuntimeError::ProtocolAdapter(ProtocolAdapterError::InvalidResponse { .. }) => {
|
||||
+ ExecutionErrorCode::UpstreamStatusError
|
||||
+ }
|
||||
+ other => panic!("unexpected test fixture: {other:?}"),
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+fn is_ambiguous_mutation(method: HttpMethod, dispatch: DispatchEvidence) -> bool {
|
||||
+ MUTATING_METHODS.contains(&method) && dispatch == DispatchEvidence::MayHaveDispatched
|
||||
+}
|
||||
+
|
||||
+fn operation(method: HttpMethod) -> RuntimeOperation {
|
||||
+ RuntimeOperation {
|
||||
+ operation_id: crank_core::OperationId::new("certainty_test"),
|
||||
+ operation_version: 1,
|
||||
+ tool_name: "certainty_test".to_owned(),
|
||||
+ protocol: Protocol::Rest,
|
||||
+ target: Target::Rest(RestTarget {
|
||||
+ base_url: "https://example.invalid".to_owned(),
|
||||
+ method,
|
||||
+ path_template: "/items".to_owned(),
|
||||
+ static_headers: BTreeMap::new(),
|
||||
+ request_contract: None,
|
||||
+ response_contract: Vec::new(),
|
||||
+ multipart_field_mime_types: BTreeMap::new(),
|
||||
+ }),
|
||||
+ input_schema: empty_schema(),
|
||||
+ output_schema: empty_schema(),
|
||||
+ input_mapping: MappingSet::default(),
|
||||
+ output_mapping: MappingSet::default(),
|
||||
+ execution_config: crank_core::ExecutionConfig::default(),
|
||||
+ tool_description: ToolDescription {
|
||||
+ title: "Certainty test".to_owned(),
|
||||
+ description: "Execution certainty fixture".to_owned(),
|
||||
+ tags: Vec::new(),
|
||||
+ examples: Vec::new(),
|
||||
+ },
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+fn empty_schema() -> Schema {
|
||||
+ Schema {
|
||||
+ kind: SchemaKind::Object,
|
||||
+ format: None,
|
||||
+ description: None,
|
||||
+ required: true,
|
||||
+ nullable: false,
|
||||
+ default_value: None,
|
||||
+ fields: BTreeMap::new(),
|
||||
+ items: None,
|
||||
+ enum_values: Vec::new(),
|
||||
+ variants: Vec::new(),
|
||||
+ }
|
||||
+}
|
||||
@@ -0,0 +1,5 @@
|
||||
Running tests/execution_certainty.rs (local-build/red-target/debug/deps/execution_certainty-c0ef6c3fcfc1fab0)
|
||||
running 3 tests
|
||||
test ambiguous_upstream_failures_are_unknown_only_for_dispatched_mutations ... FAILED
|
||||
test dispatch_uncertainty_allowlist_covers_uncertain_upstream_codes_and_drops_retry_delay ... FAILED
|
||||
test result: FAILED. 1 passed; 2 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
@@ -0,0 +1,60 @@
|
||||
diff --git a/tests/unit/test_check_rust_code_health.py b/tests/unit/test_check_rust_code_health.py
|
||||
index 660d147..5256d19 100644
|
||||
--- a/tests/unit/test_check_rust_code_health.py
|
||||
+++ b/tests/unit/test_check_rust_code_health.py
|
||||
@@ -41,7 +41,7 @@ class RustCodeHealthCheckTests(unittest.TestCase):
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("checking file size limits", result.stdout)
|
||||
|
||||
- def test_fails_for_new_large_rust_file(self) -> None:
|
||||
+ def test_fails_for_new_untracked_large_rust_file_in_source_scope(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
self.prepare_root(root)
|
||||
@@ -55,6 +55,46 @@ class RustCodeHealthCheckTests(unittest.TestCase):
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("apps/demo/src/large.rs has 21 lines", result.stderr)
|
||||
|
||||
+ def test_ignores_large_rust_in_nested_bmad_worktree(self) -> None:
|
||||
+ with tempfile.TemporaryDirectory() as tmp:
|
||||
+ root = Path(tmp)
|
||||
+ self.prepare_root(root)
|
||||
+ worktree = (
|
||||
+ root
|
||||
+ / ".bmad-loop"
|
||||
+ / "runs"
|
||||
+ / "epic-1"
|
||||
+ / "worktrees"
|
||||
+ / "fixture"
|
||||
+ )
|
||||
+ worktree.mkdir(parents=True)
|
||||
+ (worktree / "large.rs").write_text(
|
||||
+ "\n".join("// line" for _ in range(21)) + "\n",
|
||||
+ encoding="utf-8",
|
||||
+ )
|
||||
+
|
||||
+ result = self.run_checker(root)
|
||||
+
|
||||
+ self.assertEqual(result.returncode, 0, result.stderr)
|
||||
+
|
||||
+ def test_ignores_rust_under_nested_target_and_node_modules(self) -> None:
|
||||
+ with tempfile.TemporaryDirectory() as tmp:
|
||||
+ root = Path(tmp)
|
||||
+ self.prepare_root(root)
|
||||
+ generated_dirs = (
|
||||
+ root / "apps" / "demo" / "target" / "generated",
|
||||
+ root / "apps" / "demo" / "src" / "node_modules" / "fixture",
|
||||
+ root / "crates" / "demo" / "node_modules" / "fixture",
|
||||
+ )
|
||||
+ large_source = "\n".join("// generated" for _ in range(21)) + "\n"
|
||||
+ for directory in generated_dirs:
|
||||
+ directory.mkdir(parents=True)
|
||||
+ (directory / "large.rs").write_text(large_source, encoding="utf-8")
|
||||
+
|
||||
+ result = self.run_checker(root)
|
||||
+
|
||||
+ self.assertEqual(result.returncode, 0, result.stderr)
|
||||
+
|
||||
def test_fails_for_large_inline_test_module(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
@@ -0,0 +1,2 @@
|
||||
Ran 5 tests in 0.341s
|
||||
FAILED (failures=2)
|
||||
@@ -0,0 +1,193 @@
|
||||
--- a/src/pool/inner.rs
|
||||
+++ b/src/pool/inner.rs
|
||||
@@ -1,3 +1,9 @@
|
||||
+// Local CranK pool patch: this file is patched from the upstream `sqlx-core`
|
||||
+// 0.9.0 source. The changes reserve `num_idle` before publishing an idle
|
||||
+// connection and bound each pool maintenance scan by the pool capacity.
|
||||
+// See ../../../../docs/dependency-patches/sqlx-core-0.9.0.md for provenance,
|
||||
+// the exact patch and the regression tests. Upstream copyright and license
|
||||
+// notices are unchanged.
|
||||
use super::connection::{Floating, Idle, Live};
|
||||
use crate::connection::ConnectOptions;
|
||||
use crate::connection::Connection;
|
||||
@@ -206,15 +212,15 @@
|
||||
|
||||
let Floating { inner: idle, guard } = floating.into_idle();
|
||||
|
||||
- if self.idle_conns.push(idle).is_err() {
|
||||
+ let published = publish_idle_connection(&self.num_idle, move || {
|
||||
+ // NOTE: we need to make sure we drop the permit *after* we push to the idle queue
|
||||
+ // don't decrease the size
|
||||
+ self.idle_conns.push(idle).map(|()| guard.release_permit())
|
||||
+ });
|
||||
+
|
||||
+ if published.is_err() {
|
||||
panic!("BUG: connection queue overflow in release()");
|
||||
}
|
||||
-
|
||||
- // NOTE: we need to make sure we drop the permit *after* we push to the idle queue
|
||||
- // don't decrease the size
|
||||
- guard.release_permit();
|
||||
-
|
||||
- self.num_idle.fetch_add(1, Ordering::AcqRel);
|
||||
}
|
||||
|
||||
/// Try to atomically increment the pool size for a new connection.
|
||||
@@ -438,6 +444,37 @@
|
||||
}
|
||||
}
|
||||
|
||||
+/// Reserves the idle-connection slot for a publication and runs `publish`.
|
||||
+///
|
||||
+/// `publish` performs the actual publication (pushing onto `idle_conns` and
|
||||
+/// releasing the semaphore permit). The `num_idle` counter is reserved *before*
|
||||
+/// `publish` so a concurrent `pop_idle` cannot underflow it between the queue
|
||||
+/// push and the counter update. If `publish` fails (the idle queue rejects the
|
||||
+/// connection), the reservation is rolled back before the error is returned to
|
||||
+/// the caller.
|
||||
+fn publish_idle_connection<F, E>(num_idle: &AtomicUsize, publish: F) -> Result<(), E>
|
||||
+where
|
||||
+ F: FnOnce() -> Result<(), E>,
|
||||
+{
|
||||
+ num_idle.fetch_add(1, Ordering::AcqRel);
|
||||
+
|
||||
+ if let Err(error) = publish() {
|
||||
+ num_idle.fetch_sub(1, Ordering::AcqRel);
|
||||
+ return Err(error);
|
||||
+ }
|
||||
+
|
||||
+ Ok(())
|
||||
+}
|
||||
+
|
||||
+/// Bounds the number of idle connections inspected per maintenance cycle.
|
||||
+///
|
||||
+/// `num_idle` can transiently exceed the number of connections actually queued
|
||||
+/// during a publication race, so the maintenance scan is capped by the pool
|
||||
+/// capacity to keep each cycle bounded.
|
||||
+fn maintenance_batch_size(num_idle: usize, capacity: usize) -> usize {
|
||||
+ cmp::min(num_idle, capacity)
|
||||
+}
|
||||
+
|
||||
impl<DB: Database> Drop for PoolInner<DB> {
|
||||
fn drop(&mut self) {
|
||||
self.mark_closed();
|
||||
@@ -545,7 +582,11 @@
|
||||
// and if we have fewer than min_connections after reaping a connection,
|
||||
// open a new one immediately. Note that other connections may be popped from
|
||||
// the queue in the meantime - that's fine, there is no harm in checking more
|
||||
- for _ in 0..pool.num_idle() {
|
||||
+ let batch_size = maintenance_batch_size(
|
||||
+ pool.num_idle(),
|
||||
+ pool.options.max_connections as usize,
|
||||
+ );
|
||||
+ for _ in 0..batch_size {
|
||||
if let Some(conn) = pool.try_acquire() {
|
||||
if is_beyond_idle_timeout(&conn, &pool.options)
|
||||
|| is_beyond_max_lifetime(&conn, &pool.options)
|
||||
@@ -621,3 +662,106 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
+
|
||||
+#[cfg(test)]
|
||||
+mod tests {
|
||||
+ use super::{maintenance_batch_size, publish_idle_connection};
|
||||
+ use crossbeam_queue::ArrayQueue;
|
||||
+ use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
+ use std::sync::{Arc, Barrier};
|
||||
+ use std::thread;
|
||||
+
|
||||
+ #[test]
|
||||
+ fn maintenance_batch_size_bounds_scan_by_capacity() {
|
||||
+ let capacity = 8;
|
||||
+
|
||||
+ assert_eq!(maintenance_batch_size(0, capacity), 0);
|
||||
+ assert_eq!(maintenance_batch_size(1, capacity), 1);
|
||||
+ assert_eq!(maintenance_batch_size(capacity, capacity), capacity);
|
||||
+ assert_eq!(maintenance_batch_size(capacity + 1, capacity), capacity);
|
||||
+ assert_eq!(maintenance_batch_size(usize::MAX, capacity), capacity);
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn publish_reserves_idle_counter_before_connection_is_visible() {
|
||||
+ const ITEM: usize = 7;
|
||||
+
|
||||
+ let queue: Arc<ArrayQueue<usize>> = Arc::new(ArrayQueue::new(4));
|
||||
+ let num_idle = Arc::new(AtomicUsize::new(0));
|
||||
+ let published = Arc::new(Barrier::new(2));
|
||||
+ let popped = Arc::new(Barrier::new(2));
|
||||
+
|
||||
+ let producer = {
|
||||
+ let queue = Arc::clone(&queue);
|
||||
+ let num_idle = Arc::clone(&num_idle);
|
||||
+ let published = Arc::clone(&published);
|
||||
+ let popped = Arc::clone(&popped);
|
||||
+ thread::spawn(move || {
|
||||
+ publish_idle_connection(num_idle.as_ref(), move || {
|
||||
+ queue
|
||||
+ .push(ITEM)
|
||||
+ .expect("queue accepts published connection");
|
||||
+ // The consumer can only pop once the connection is queued.
|
||||
+ published.wait();
|
||||
+ // Keep the closure open until the concurrent pop has happened so the
|
||||
+ // counter is observed at the exact moment the connection was visible.
|
||||
+ popped.wait();
|
||||
+ Ok::<(), ()>(())
|
||||
+ })
|
||||
+ .expect("publication succeeds");
|
||||
+ })
|
||||
+ };
|
||||
+
|
||||
+ let consumer = {
|
||||
+ let queue = Arc::clone(&queue);
|
||||
+ let num_idle = Arc::clone(&num_idle);
|
||||
+ let published = Arc::clone(&published);
|
||||
+ let popped = Arc::clone(&popped);
|
||||
+ thread::spawn(move || {
|
||||
+ published.wait();
|
||||
+ let item = queue.pop().expect("published connection is visible");
|
||||
+ let previous = num_idle.fetch_sub(1, Ordering::AcqRel);
|
||||
+ // Do not assert here: on the buggy ordering the producer would still be
|
||||
+ // waiting for this barrier and an early panic would deadlock the test.
|
||||
+ popped.wait();
|
||||
+ (item, previous)
|
||||
+ })
|
||||
+ };
|
||||
+
|
||||
+ let (item, previous) = consumer.join().expect("consumer does not panic");
|
||||
+ producer.join().expect("producer does not panic");
|
||||
+
|
||||
+ assert_eq!(item, ITEM);
|
||||
+ assert!(
|
||||
+ previous > 0,
|
||||
+ "idle counter must be reserved before the connection is visible, saw {previous}"
|
||||
+ );
|
||||
+ assert_eq!(
|
||||
+ previous, 1,
|
||||
+ "a single publication must reserve exactly one idle slot"
|
||||
+ );
|
||||
+ assert_eq!(
|
||||
+ num_idle.load(Ordering::Acquire),
|
||||
+ 0,
|
||||
+ "idle counter must settle back to zero"
|
||||
+ );
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn publish_rolls_back_idle_counter_when_publication_fails() {
|
||||
+ // Production `release()` returns the rejected `Idle<DB>` as the error of
|
||||
+ // this callback; a string error exercises the same helper contract
|
||||
+ // without constructing a database connection.
|
||||
+ let num_idle = AtomicUsize::new(0);
|
||||
+
|
||||
+ let result: Result<(), &'static str> =
|
||||
+ publish_idle_connection(&num_idle, || Err("publish failed"));
|
||||
+
|
||||
+ assert_eq!(result, Err("publish failed"));
|
||||
+ assert_eq!(
|
||||
+ num_idle.load(Ordering::Acquire),
|
||||
+ 0,
|
||||
+ "failed publication must not leak an idle slot"
|
||||
+ );
|
||||
+ }
|
||||
+}
|
||||
@@ -0,0 +1,3 @@
|
||||
Running unittests src/lib.rs (isolated-build/sqlx-target/debug/deps/sqlx_core-83f2250fda96ed55)
|
||||
running 5 tests
|
||||
test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
@@ -0,0 +1,176 @@
|
||||
--- a/src/pool/inner.rs
|
||||
+++ b/src/pool/inner.rs
|
||||
@@ -206,15 +206,21 @@
|
||||
|
||||
let Floating { inner: idle, guard } = floating.into_idle();
|
||||
|
||||
- if self.idle_conns.push(idle).is_err() {
|
||||
- panic!("BUG: connection queue overflow in release()");
|
||||
- }
|
||||
+ let published = publish_idle_connection(&self.num_idle, move || {
|
||||
+ if self.idle_conns.push(idle).is_err() {
|
||||
+ panic!("BUG: connection queue overflow in release()");
|
||||
+ }
|
||||
|
||||
- // NOTE: we need to make sure we drop the permit *after* we push to the idle queue
|
||||
- // don't decrease the size
|
||||
- guard.release_permit();
|
||||
+ // NOTE: we need to make sure we drop the permit *after* we push to the idle queue
|
||||
+ // don't decrease the size
|
||||
+ guard.release_permit();
|
||||
|
||||
- self.num_idle.fetch_add(1, Ordering::AcqRel);
|
||||
+ Ok::<(), std::convert::Infallible>(())
|
||||
+ });
|
||||
+
|
||||
+ if let Err(never) = published {
|
||||
+ match never {}
|
||||
+ }
|
||||
}
|
||||
|
||||
/// Try to atomically increment the pool size for a new connection.
|
||||
@@ -438,6 +444,29 @@
|
||||
}
|
||||
}
|
||||
|
||||
+/// Reserves the idle-connection slot for a publication and runs `publish`.
|
||||
+///
|
||||
+/// `publish` performs the actual publication (pushing onto `idle_conns` and
|
||||
+/// releasing the semaphore permit). The `num_idle` counter is updated *after*
|
||||
+/// `publish` returns, matching upstream ordering.
|
||||
+fn publish_idle_connection<F, E>(num_idle: &AtomicUsize, publish: F) -> Result<(), E>
|
||||
+where
|
||||
+ F: FnOnce() -> Result<(), E>,
|
||||
+{
|
||||
+ publish()?;
|
||||
+ num_idle.fetch_add(1, Ordering::AcqRel);
|
||||
+ Ok(())
|
||||
+}
|
||||
+
|
||||
+/// Bounds the number of idle connections inspected per maintenance cycle.
|
||||
+///
|
||||
+/// The maintenance task iterates `0..num_idle`; upstream returns the raw
|
||||
+/// counter.
|
||||
+fn maintenance_batch_size(num_idle: usize, capacity: usize) -> usize {
|
||||
+ let _ = capacity;
|
||||
+ num_idle
|
||||
+}
|
||||
+
|
||||
impl<DB: Database> Drop for PoolInner<DB> {
|
||||
fn drop(&mut self) {
|
||||
self.mark_closed();
|
||||
@@ -545,7 +574,11 @@
|
||||
// and if we have fewer than min_connections after reaping a connection,
|
||||
// open a new one immediately. Note that other connections may be popped from
|
||||
// the queue in the meantime - that's fine, there is no harm in checking more
|
||||
- for _ in 0..pool.num_idle() {
|
||||
+ let batch_size = maintenance_batch_size(
|
||||
+ pool.num_idle(),
|
||||
+ pool.options.max_connections as usize,
|
||||
+ );
|
||||
+ for _ in 0..batch_size {
|
||||
if let Some(conn) = pool.try_acquire() {
|
||||
if is_beyond_idle_timeout(&conn, &pool.options)
|
||||
|| is_beyond_max_lifetime(&conn, &pool.options)
|
||||
@@ -621,3 +654,101 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
+
|
||||
+#[cfg(test)]
|
||||
+mod tests {
|
||||
+ use super::{maintenance_batch_size, publish_idle_connection};
|
||||
+ use crossbeam_queue::ArrayQueue;
|
||||
+ use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
+ use std::sync::{Arc, Barrier};
|
||||
+ use std::thread;
|
||||
+
|
||||
+ #[test]
|
||||
+ fn maintenance_batch_size_bounds_scan_by_capacity() {
|
||||
+ let capacity = 8;
|
||||
+
|
||||
+ assert_eq!(maintenance_batch_size(0, capacity), 0);
|
||||
+ assert_eq!(maintenance_batch_size(1, capacity), 1);
|
||||
+ assert_eq!(maintenance_batch_size(capacity, capacity), capacity);
|
||||
+ assert_eq!(maintenance_batch_size(capacity + 1, capacity), capacity);
|
||||
+ assert_eq!(maintenance_batch_size(usize::MAX, capacity), capacity);
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn publish_reserves_idle_counter_before_connection_is_visible() {
|
||||
+ const ITEM: usize = 7;
|
||||
+
|
||||
+ let queue: Arc<ArrayQueue<usize>> = Arc::new(ArrayQueue::new(4));
|
||||
+ let num_idle = Arc::new(AtomicUsize::new(0));
|
||||
+ let published = Arc::new(Barrier::new(2));
|
||||
+ let popped = Arc::new(Barrier::new(2));
|
||||
+
|
||||
+ let producer = {
|
||||
+ let queue = Arc::clone(&queue);
|
||||
+ let num_idle = Arc::clone(&num_idle);
|
||||
+ let published = Arc::clone(&published);
|
||||
+ let popped = Arc::clone(&popped);
|
||||
+ thread::spawn(move || {
|
||||
+ publish_idle_connection(num_idle.as_ref(), move || {
|
||||
+ queue.push(ITEM).expect("queue accepts published connection");
|
||||
+ // The consumer can only pop once the connection is queued.
|
||||
+ published.wait();
|
||||
+ // Keep the closure open until the concurrent pop has happened so the
|
||||
+ // counter is observed at the exact moment the connection was visible.
|
||||
+ popped.wait();
|
||||
+ Ok::<(), ()>(())
|
||||
+ })
|
||||
+ .expect("publication succeeds");
|
||||
+ })
|
||||
+ };
|
||||
+
|
||||
+ let consumer = {
|
||||
+ let queue = Arc::clone(&queue);
|
||||
+ let num_idle = Arc::clone(&num_idle);
|
||||
+ let published = Arc::clone(&published);
|
||||
+ let popped = Arc::clone(&popped);
|
||||
+ thread::spawn(move || {
|
||||
+ published.wait();
|
||||
+ let item = queue.pop().expect("published connection is visible");
|
||||
+ let previous = num_idle.fetch_sub(1, Ordering::AcqRel);
|
||||
+ // Do not assert here: on the buggy ordering the producer would still be
|
||||
+ // waiting for this barrier and an early panic would deadlock the test.
|
||||
+ popped.wait();
|
||||
+ (item, previous)
|
||||
+ })
|
||||
+ };
|
||||
+
|
||||
+ let (item, previous) = consumer.join().expect("consumer does not panic");
|
||||
+ producer.join().expect("producer does not panic");
|
||||
+
|
||||
+ assert_eq!(item, ITEM);
|
||||
+ assert!(
|
||||
+ previous > 0,
|
||||
+ "idle counter must be reserved before the connection is visible, saw {previous}"
|
||||
+ );
|
||||
+ assert_eq!(
|
||||
+ previous, 1,
|
||||
+ "a single publication must reserve exactly one idle slot"
|
||||
+ );
|
||||
+ assert_eq!(
|
||||
+ num_idle.load(Ordering::Acquire),
|
||||
+ 0,
|
||||
+ "idle counter must settle back to zero"
|
||||
+ );
|
||||
+ }
|
||||
+
|
||||
+ #[test]
|
||||
+ fn publish_rolls_back_idle_counter_when_publication_fails() {
|
||||
+ let num_idle = AtomicUsize::new(0);
|
||||
+
|
||||
+ let result: Result<(), &'static str> =
|
||||
+ publish_idle_connection(&num_idle, || Err("publish failed"));
|
||||
+
|
||||
+ assert_eq!(result, Err("publish failed"));
|
||||
+ assert_eq!(
|
||||
+ num_idle.load(Ordering::Acquire),
|
||||
+ 0,
|
||||
+ "failed publication must not leak an idle slot"
|
||||
+ );
|
||||
+ }
|
||||
+}
|
||||
@@ -0,0 +1,5 @@
|
||||
Running unittests src/lib.rs (isolated-build/sqlx-target/debug/deps/sqlx_core-83f2250fda96ed55)
|
||||
running 3 tests
|
||||
test pool::inner::tests::maintenance_batch_size_bounds_scan_by_capacity ... FAILED
|
||||
test pool::inner::tests::publish_reserves_idle_counter_before_connection_is_visible ... FAILED
|
||||
test result: FAILED. 1 passed; 2 failed; 0 ignored; 0 measured; 2 filtered out; finished in 0.00s
|
||||
@@ -0,0 +1,15 @@
|
||||
Ran 159 tests in 32.108s
|
||||
OK
|
||||
Community scope check passed (957 files scanned)
|
||||
runtime configuration contract check passed
|
||||
config boundary check passed: files=270
|
||||
Metrics boundary check passed: files=450
|
||||
Rust boundary check passed
|
||||
config boundary check passed: files=270
|
||||
migration boundary check passed: files=297
|
||||
Metrics boundary check passed: files=450
|
||||
Execution boundary check passed
|
||||
Rust code health: checking file size limits
|
||||
Rust code health: checking large inline test modules
|
||||
Running unittests src/lib.rs (target/debug/deps/admin_api-6e005e394d271023)
|
||||
running 39 tests
|
||||
@@ -0,0 +1,32 @@
|
||||
Ran 156 tests in 34.606s
|
||||
OK
|
||||
Community scope check passed (846 files scanned)
|
||||
runtime configuration contract check passed
|
||||
config boundary check passed: files=270
|
||||
Metrics boundary check passed: files=450
|
||||
Rust boundary check passed
|
||||
config boundary check passed: files=270
|
||||
migration boundary check passed: files=297
|
||||
Metrics boundary check passed: files=450
|
||||
Execution boundary check passed
|
||||
Rust code health: checking file size limits
|
||||
Rust code health: checking large inline test modules
|
||||
Running unittests src/lib.rs (target/debug/deps/admin_api-5560a63b5bf3a0db)
|
||||
running 39 tests
|
||||
test result: ok. 39 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 35.53s
|
||||
Running unittests src/main.rs (target/debug/deps/admin_api-fae2dd814ba9ed4a)
|
||||
running 0 tests
|
||||
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running unittests src/bin/crank-migrate.rs (target/debug/deps/crank_migrate-bbd490202e416a13)
|
||||
running 0 tests
|
||||
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running tests/config_startup.rs (target/debug/deps/config_startup-55416d2755079c57)
|
||||
running 6 tests
|
||||
test result: ok. 6 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 47.97s
|
||||
Running tests/dc08.rs (target/debug/deps/dc08-188f4276d178333d)
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 33.68s
|
||||
Running tests/integration.rs (target/debug/deps/integration-299c6911c2a4784d)
|
||||
running 148 tests
|
||||
error: recipe `test` failed on line 45 with exit code 101
|
||||
error: recipe `verify` failed on line 71 with exit code 101
|
||||
@@ -0,0 +1,29 @@
|
||||
Ran 156 tests in 30.303s
|
||||
OK
|
||||
Community scope check passed (846 files scanned)
|
||||
runtime configuration contract check passed
|
||||
config boundary check passed: files=270
|
||||
Metrics boundary check passed: files=450
|
||||
Rust boundary check passed
|
||||
config boundary check passed: files=270
|
||||
migration boundary check passed: files=297
|
||||
Metrics boundary check passed: files=450
|
||||
Execution boundary check passed
|
||||
Rust code health: checking file size limits
|
||||
Rust code health: checking large inline test modules
|
||||
Running unittests src/lib.rs (target/debug/deps/admin_api-5560a63b5bf3a0db)
|
||||
running 39 tests
|
||||
test result: ok. 39 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 39.50s
|
||||
Running unittests src/main.rs (target/debug/deps/admin_api-fae2dd814ba9ed4a)
|
||||
running 0 tests
|
||||
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running unittests src/bin/crank-migrate.rs (target/debug/deps/crank_migrate-bbd490202e416a13)
|
||||
running 0 tests
|
||||
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running tests/config_startup.rs (target/debug/deps/config_startup-55416d2755079c57)
|
||||
running 6 tests
|
||||
test master_key_mismatch_blocks_startup_with_safe_diagnostic ... FAILED
|
||||
test real_admin_startup_runs_immediate_import_maintenance ... FAILED
|
||||
test result: FAILED. 4 passed; 2 failed; 0 ignored; 0 measured; 0 filtered out; finished in 48.46s
|
||||
error: recipe `test` failed on line 45 with exit code 101
|
||||
error: recipe `verify` failed on line 71 with exit code 101
|
||||
@@ -0,0 +1,10 @@
|
||||
Ran 156 tests in 30.045s
|
||||
OK
|
||||
Community scope check failed:
|
||||
error: vendor/sqlx-core/LICENSE-APACHE:162: forbidden marker `commercial` # community-scope: allow=commercial
|
||||
error: vendor/sqlx-core/src/config/migrate.rs:40: forbidden marker `tenant` # community-scope: allow=tenant
|
||||
error: vendor/sqlx-core/src/config/reference.toml:178: forbidden marker `tenant` # community-scope: allow=tenant
|
||||
error: vendor/sqlx-core/src/migrate/migrator.rs:101: forbidden marker `tenant` # community-scope: allow=tenant
|
||||
error: vendor/sqlx-core/src/pool/options.rs:299: forbidden marker `billing` # community-scope: allow=billing
|
||||
error: recipe `community-scope-check` failed on line 15 with exit code 1
|
||||
error: recipe `verify` failed on line 62 with exit code 1
|
||||
@@ -0,0 +1,317 @@
|
||||
Ran 159 tests in 30.098s
|
||||
OK
|
||||
Community scope check passed (957 files scanned)
|
||||
runtime configuration contract check passed
|
||||
config boundary check passed: files=270
|
||||
Metrics boundary check passed: files=450
|
||||
Rust boundary check passed
|
||||
config boundary check passed: files=270
|
||||
migration boundary check passed: files=297
|
||||
Metrics boundary check passed: files=450
|
||||
Execution boundary check passed
|
||||
Rust code health: checking file size limits
|
||||
Rust code health: checking large inline test modules
|
||||
Running unittests src/lib.rs (target/debug/deps/admin_api-6e005e394d271023)
|
||||
running 39 tests
|
||||
test result: ok. 39 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 28.57s
|
||||
Running unittests src/main.rs (target/debug/deps/admin_api-585fcfaa93e949af)
|
||||
running 0 tests
|
||||
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running unittests src/bin/crank-migrate.rs (target/debug/deps/crank_migrate-0408cbf6cf01d000)
|
||||
running 0 tests
|
||||
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running tests/config_startup.rs (target/debug/deps/config_startup-8202fb87159e5d63)
|
||||
running 6 tests
|
||||
test result: ok. 6 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 38.40s
|
||||
Running tests/dc08.rs (target/debug/deps/dc08-feaa94258fc47ede)
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 30.81s
|
||||
Running tests/integration.rs (target/debug/deps/integration-14490fd117dc815e)
|
||||
running 148 tests
|
||||
test result: ok. 148 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 551.53s
|
||||
Running tests/migration_command.rs (target/debug/deps/migration_command-2a2a3578be8af14a)
|
||||
running 7 tests
|
||||
test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 41.55s
|
||||
Running tests/product_metrics.rs (target/debug/deps/product_metrics-ed41cfc63891409a)
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 29.21s
|
||||
Running tests/request_context.rs (target/debug/deps/request_context-b45c764910742a43)
|
||||
running 5 tests
|
||||
test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
|
||||
Running tests/request_context_parent.rs (target/debug/deps/request_context_parent-84198ba634d8385e)
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running tests/unit.rs (target/debug/deps/unit-535bb923a4ebf554)
|
||||
running 8 tests
|
||||
test result: ok. 8 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running unittests src/lib.rs (target/debug/deps/crank_adapter_rest-d23d0bec6e21f0fc)
|
||||
running 5 tests
|
||||
test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running tests/integration.rs (target/debug/deps/integration-2c59230bfe3fad2d)
|
||||
running 35 tests
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 34 filtered out; finished in 1.54s
|
||||
test result: ok. 35 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 1.61s
|
||||
Running unittests src/lib.rs (target/debug/deps/crank_artifacts-41120e054a6b8bcd)
|
||||
running 0 tests
|
||||
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running tests/artifact_store.rs (target/debug/deps/artifact_store-c7e63fbdd5dd7c1d)
|
||||
running 25 tests
|
||||
running 1 test
|
||||
running 1 test
|
||||
running 1 test
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 24 filtered out; finished in 0.01s
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 24 filtered out; finished in 0.01s
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 24 filtered out; finished in 0.01s
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 24 filtered out; finished in 0.01s
|
||||
test result: ok. 25 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.25s
|
||||
Running tests/artifact_store_io.rs (target/debug/deps/artifact_store_io-9336360ab7222d48)
|
||||
running 7 tests
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 6 filtered out; finished in 0.00s
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 6 filtered out; finished in 0.00s
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 6 filtered out; finished in 0.00s
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 6 filtered out; finished in 0.00s
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 6 filtered out; finished in 0.00s
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 6 filtered out; finished in 0.00s
|
||||
running 1 test
|
||||
running 1 test
|
||||
running 1 test
|
||||
running 1 test
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 6 filtered out; finished in 0.00s
|
||||
test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.05s
|
||||
Running tests/reconciliation.rs (target/debug/deps/reconciliation-26c63ea67fe01006)
|
||||
running 25 tests
|
||||
running 1 test
|
||||
running 1 test
|
||||
running 1 test
|
||||
running 1 test
|
||||
running 1 test
|
||||
test result: ok. 25 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.08s
|
||||
Running unittests src/lib.rs (target/debug/deps/crank_community_auth-ec46cb3b2738d2ce)
|
||||
running 5 tests
|
||||
test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.37s
|
||||
Running unittests src/lib.rs (target/debug/deps/crank_community_mcp-29356323dae0bfbb)
|
||||
running 17 tests
|
||||
test result: ok. 17 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
|
||||
Running tests/integration.rs (target/debug/deps/integration-fa84ee74c1eb0674)
|
||||
running 3 tests
|
||||
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 32.76s
|
||||
Running tests/session_metrics.rs (target/debug/deps/session_metrics-3072f0726cec1fe8)
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.12s
|
||||
Running tests/unit.rs (target/debug/deps/unit-dc3d3d6088e3a6f9)
|
||||
running 17 tests
|
||||
test result: ok. 17 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.16s
|
||||
Running unittests src/lib.rs (target/debug/deps/crank_config-070baa6a5d466676)
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.11s
|
||||
Running unittests src/bin/crank-config-contract.rs (target/debug/deps/crank_config_contract-fc8434371655ba83)
|
||||
running 0 tests
|
||||
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running tests/contract.rs (target/debug/deps/contract-fe6dc5cfca7a1884)
|
||||
running 18 tests
|
||||
test result: ok. 18 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.05s
|
||||
Running tests/generation.rs (target/debug/deps/generation-d19623099785140f)
|
||||
running 3 tests
|
||||
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
|
||||
Running tests/redaction.rs (target/debug/deps/redaction-6f71674fd9f278cf)
|
||||
running 5 tests
|
||||
test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running unittests src/lib.rs (target/debug/deps/crank_core-c400981d4f0fab5c)
|
||||
running 43 tests
|
||||
test result: ok. 43 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
|
||||
Running tests/correlation.rs (target/debug/deps/correlation-11defa265401293e)
|
||||
running 6 tests
|
||||
test result: ok. 6 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running tests/execution.rs (target/debug/deps/execution-159bd574119ea9a0)
|
||||
running 6 tests
|
||||
test result: ok. 6 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running tests/unit.rs (target/debug/deps/unit-b9b5fb16ddf212a0)
|
||||
running 19 tests
|
||||
test result: ok. 19 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running unittests src/lib.rs (target/debug/deps/crank_import-544e5bbb7f3c11b5)
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running tests/corpus.rs (target/debug/deps/corpus-6865edaf8b86098a)
|
||||
running 3 tests
|
||||
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 1.21s
|
||||
Running tests/coverage.rs (target/debug/deps/coverage-151fa5168d4102e1)
|
||||
running 7 tests
|
||||
test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
|
||||
Running tests/http_contract_regressions.rs (target/debug/deps/http_contract_regressions-b85b270b46dff716)
|
||||
running 9 tests
|
||||
test result: ok. 9 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.02s
|
||||
Running tests/http_replay.rs (target/debug/deps/http_replay-138e3fba2e7cca29)
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
|
||||
Running tests/legacy_http_contract.rs (target/debug/deps/legacy_http_contract-baf0c5f9f5c73128)
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running tests/normalization_details.rs (target/debug/deps/normalization_details-226545eab1f0783b)
|
||||
running 11 tests
|
||||
test result: ok. 11 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.03s
|
||||
Running tests/path_parameter_inheritance.rs (target/debug/deps/path_parameter_inheritance-0f5f0b281d25d025)
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
|
||||
Running tests/preview.rs (target/debug/deps/preview-f2d2298c27753d5b)
|
||||
running 18 tests
|
||||
test result: ok. 18 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.03s
|
||||
Running tests/reference_resolution.rs (target/debug/deps/reference_resolution-255e68b1c43db563)
|
||||
running 24 tests
|
||||
test result: ok. 24 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.04s
|
||||
Running tests/schema_projection.rs (target/debug/deps/schema_projection-48470fb7231c7205)
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running tests/security_schemes.rs (target/debug/deps/security_schemes-1c1de0987b9b1d80)
|
||||
running 17 tests
|
||||
test result: ok. 17 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.04s
|
||||
Running tests/security_scope.rs (target/debug/deps/security_scope-7c2951f629e03b7b)
|
||||
running 13 tests
|
||||
test result: ok. 13 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.03s
|
||||
Running tests/swagger2_contract.rs (target/debug/deps/swagger2_contract-40ec5f8667924e06)
|
||||
running 3 tests
|
||||
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running tests/unit.rs (target/debug/deps/unit-0700eb028407de73)
|
||||
running 16 tests
|
||||
test result: ok. 16 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.06s
|
||||
Running unittests src/lib.rs (target/debug/deps/crank_mapping-9d6aad2294807abb)
|
||||
running 11 tests
|
||||
test result: ok. 11 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running unittests src/lib.rs (target/debug/deps/crank_metrics-aa0f02dc4fbfcae2)
|
||||
running 0 tests
|
||||
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running unittests src/bin/crank-metrics-contract.rs (target/debug/deps/crank_metrics_contract-b1a91ac8968d20ad)
|
||||
running 0 tests
|
||||
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running tests/cardinality.rs (target/debug/deps/cardinality-607b7cbd207baafb)
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 20.50s
|
||||
Running tests/contract.rs (target/debug/deps/contract-77b674aa0e5444a3)
|
||||
running 8 tests
|
||||
test result: ok. 8 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
|
||||
Running tests/contract_cli.rs (target/debug/deps/contract_cli-f8691aee29fa8ee3)
|
||||
running 2 tests
|
||||
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
|
||||
Running tests/exemplars.rs (target/debug/deps/exemplars-88c3dc9405c1c046)
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running tests/overhead.rs (target/debug/deps/overhead-5bce972d208e5997)
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.46s
|
||||
Running tests/schema_v1.rs (target/debug/deps/schema_v1-bea7a91372384f7f)
|
||||
running 8 tests
|
||||
test result: ok. 8 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
|
||||
Running unittests src/lib.rs (target/debug/deps/crank_observability-da302f9190b524cf)
|
||||
running 28 tests
|
||||
test result: ok. 28 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 1.34s
|
||||
Running tests/critical_errors.rs (target/debug/deps/critical_errors-c3e3722ec239539f)
|
||||
running 3 tests
|
||||
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running tests/http_metrics.rs (target/debug/deps/http_metrics-4e4162b88cf3711e)
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.02s
|
||||
Running tests/incidents.rs (target/debug/deps/incidents-86bce972049d273a)
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running tests/json_logging.rs (target/debug/deps/json_logging-c0df2f37607b623e)
|
||||
running 13 tests
|
||||
test result: ok. 13 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
|
||||
Running tests/lifecycle.rs (target/debug/deps/lifecycle-46d8c165c17407d5)
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.06s
|
||||
Running tests/metrics_signals.rs (target/debug/deps/metrics_signals-9a861803ff8e46e0)
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
|
||||
Running tests/otlp.rs (target/debug/deps/otlp-ffcd27be7652a473)
|
||||
running 3 tests
|
||||
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running tests/prometheus.rs (target/debug/deps/prometheus-9e36c99a960244db)
|
||||
running 8 tests
|
||||
test result: ok. 8 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
|
||||
Running tests/propagation.rs (target/debug/deps/propagation-454f73fe9dc1ed10)
|
||||
running 2 tests
|
||||
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running tests/redaction.rs (target/debug/deps/redaction-8ce35caa2bed9cfb)
|
||||
running 10 tests
|
||||
test result: ok. 10 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running tests/request_correlation.rs (target/debug/deps/request_correlation-f2f83f44f2a67e78)
|
||||
running 2 tests
|
||||
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running unittests src/lib.rs (target/debug/deps/crank_registry-aca7f3670abc3d80)
|
||||
running 14 tests
|
||||
test result: ok. 14 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 2.46s
|
||||
Running tests/integration.rs (target/debug/deps/integration-baf76c15612f28e7)
|
||||
running 156 tests
|
||||
test integration::observability::production_size_invocation_history_queries_stay_bounded ... ignored, production-size query-plan evidence: inserts 1,000,000 invocation_logs rows
|
||||
test result: ok. 155 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out; finished in 459.35s
|
||||
Running unittests src/lib.rs (target/debug/deps/crank_runtime-aa6c1206011d24ba)
|
||||
running 42 tests
|
||||
test result: ok. 42 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.02s
|
||||
Running tests/execution_certainty.rs (target/debug/deps/execution_certainty-a9b32f4a1af59673)
|
||||
running 3 tests
|
||||
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running tests/http_contract.rs (target/debug/deps/http_contract-109053799cd46c1c)
|
||||
running 5 tests
|
||||
test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.02s
|
||||
Running tests/http_contract_wire.rs (target/debug/deps/http_contract_wire-4a305461d75a4411)
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.03s
|
||||
Running tests/integration.rs (target/debug/deps/integration-35ed06bd243cd089)
|
||||
running 11 tests
|
||||
test result: ok. 11 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 2.33s
|
||||
Running tests/product_metrics.rs (target/debug/deps/product_metrics-91a1acee169c53ca)
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
|
||||
Running tests/stages.rs (target/debug/deps/stages-17b341afb79af23c)
|
||||
running 10 tests
|
||||
test result: ok. 10 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.03s
|
||||
Running tests/unit.rs (target/debug/deps/unit-77074afab2ab43de)
|
||||
running 13 tests
|
||||
test result: ok. 13 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.02s
|
||||
Running unittests src/lib.rs (target/debug/deps/crank_schema-cae2b0d9d1382536)
|
||||
running 10 tests
|
||||
test result: ok. 10 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
|
||||
Running unittests src/lib.rs (target/debug/deps/crank_test_support-3c1a3207cad65f25)
|
||||
running 0 tests
|
||||
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running unittests src/lib.rs (target/debug/deps/crank_trace-6528c24c70cb8e45)
|
||||
running 0 tests
|
||||
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running tests/contract.rs (target/debug/deps/contract-3dff1581256e02c9)
|
||||
running 2 tests
|
||||
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running unittests src/lib.rs (target/debug/deps/mcp_server-5b408f74dfabc76b)
|
||||
running 0 tests
|
||||
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running unittests src/main.rs (target/debug/deps/mcp_server-3d50d83a9ccf15a5)
|
||||
running 0 tests
|
||||
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
|
||||
Running tests/config_startup.rs (target/debug/deps/config_startup-af40d04cfc300de2)
|
||||
running 4 tests
|
||||
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 39.22s
|
||||
Running tests/dc08.rs (target/debug/deps/dc08-bdeb149d1f8373fe)
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 28.89s
|
||||
Running tests/execution_stages.rs (target/debug/deps/execution_stages-5cc1c75032712afc)
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 29.45s
|
||||
Running tests/integration.rs (target/debug/deps/integration-15c63b8c239f4af1)
|
||||
running 41 tests
|
||||
test result: ok. 41 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 135.87s
|
||||
Running tests/onboarding.rs (target/debug/deps/onboarding-e8f885aa0ca848a5)
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 32.81s
|
||||
Running tests/product_metrics.rs (target/debug/deps/product_metrics-10e1573959c2ea33)
|
||||
running 1 test
|
||||
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 30.24s
|
||||
Running tests/request_context.rs (target/debug/deps/request_context-83d66791ddb98021)
|
||||
running 3 tests
|
||||
test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 41.91s
|
||||
@@ -0,0 +1,950 @@
|
||||
{
|
||||
"version": "2026.10.04.1",
|
||||
"scope": "Epic 1 development acceptance after retrospective repairs; external qualification separate",
|
||||
"baseline_commit": "c172e3cfa235ab9e91b5996e9cab506fabb889f8",
|
||||
"implementation_revision": "9496b19736c275ded2731dae399e04dd9a2fcce2",
|
||||
"workspace_verification_revision": "4a4922495b07b69ef8d405c74adc14d7383b5001",
|
||||
"development_verdict": "pass",
|
||||
"counts_definition": "Сумма reported harness executions; child harness учитываются отдельно, не число уникальных scenarios.",
|
||||
"historical_baseline": {
|
||||
"path": "docs/capability-baseline/results.json",
|
||||
"version": "2026.08.24.1",
|
||||
"source_revision": "767428436d3a54e60809a727044dfcec48e1f1dd",
|
||||
"disposition": "unchanged; historical manual failures not overwritten"
|
||||
},
|
||||
"environment": {
|
||||
"class": "local Linux; PostgreSQL16-alpine Testcontainers; Community real-stack/synthetic fixture",
|
||||
"toolchain": {
|
||||
"rustc": "rustc 1.96.1 (31fca3adb 2026-06-26)",
|
||||
"cargo": "cargo 1.96.1 (356927216 2026-06-26)",
|
||||
"python": "Python 3.14.7",
|
||||
"node": "v26.10.0",
|
||||
"npm": "12.2.0",
|
||||
"docker_server": "29.8.2",
|
||||
"postgres_image_repo_digests": [
|
||||
"postgres@sha256:57c72fd2a128e416c7fcc499958864df5301e940bca0a56f58fddf30ffc07777"
|
||||
]
|
||||
},
|
||||
"configuration": [
|
||||
{
|
||||
"path": "Cargo.toml",
|
||||
"sha256": "3b9045aa880d6e9e8463c90dde089407d12d1a141af82c78169b71b96e644512"
|
||||
},
|
||||
{
|
||||
"path": "Cargo.lock",
|
||||
"sha256": "afe994e31bcf1e595ce5a82e5cefbd9ebc3ebe372b929071163d0fe370c3b12b"
|
||||
},
|
||||
{
|
||||
"path": "justfile",
|
||||
"sha256": "4f7af4b6181efb7dc2219608eef4c1cb179ea225751151e9b50fe20ec58164ec"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/package-lock.json",
|
||||
"sha256": "b60165a1de830edc0d7cd0ee5e7ca83d5cc66b97c05086f4d34eacd2699d4dce"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/playwright.config.js",
|
||||
"sha256": "67b86c341d98cc5bdd41e04d9c8f456fa3ef05438f41a9ee82450e31d5226775"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/scripts/playwright-stack.sh",
|
||||
"sha256": "bd562d8cd437e326de2a2d0ff4888d2674f5d934e3d757967a9a34bd01aff420"
|
||||
}
|
||||
]
|
||||
},
|
||||
"external_qualification": {
|
||||
"human_usability_UI_13": "not_run",
|
||||
"reference": "not_run",
|
||||
"long_duration": "not_run",
|
||||
"plan": "docs/acceptance-test-plan.md"
|
||||
},
|
||||
"prior_observations_without_primary_logs": [
|
||||
{
|
||||
"status": "interrupted",
|
||||
"observation": "До перезапуска первый just verify на 1b9f7f6 остановлен SIGTERM после >20min busy loop; CPU IP sampling указал на SQLx pool maintenance/semaphore. Underflow/MAX iterator не наблюдался. 148 Admin integration cases затем прошли под debugger. Raw /tmp logs потеряны при restart; это не primary completion evidence."
|
||||
},
|
||||
{
|
||||
"status": "fail",
|
||||
"observation": "Direct-to-file capture приводил к отказу дочернего RLIMIT_FSIZE test reporter; тот же test binary с pipe capture прошёл. Raw /tmp logs потеряны; текущий gate сохраняет вывод через pipe."
|
||||
},
|
||||
{
|
||||
"status": "fail",
|
||||
"observation": "Baseline RED использовал общий target и подменил registry artifact; cache затронутых packages очищен. Raw /tmp logs потеряны; текущий baseline target отдельный."
|
||||
}
|
||||
],
|
||||
"limitations": [
|
||||
"SQLx maintenance исправлен узким tracked dependency patch с forced-interleaving RED/GREEN и bounded-batch regression; live MAX counter во время наблюдённого hang не снимался. Локальный patch нужно сопровождать до verified upstream fix.",
|
||||
"Новые automated runs не являются повторной manual acceptance всех historical UI failures."
|
||||
],
|
||||
"runs": [
|
||||
{
|
||||
"id": "runtime-red",
|
||||
"baseline_commit": "c172e3cfa235ab9e91b5996e9cab506fabb889f8",
|
||||
"command": "cargo test -p crank-runtime --test execution_certainty -- --test-threads=1",
|
||||
"exit_code": 101,
|
||||
"status": "fail",
|
||||
"counts": {
|
||||
"passed": 1,
|
||||
"rust_passed": 1,
|
||||
"tooling_passed": 0,
|
||||
"playwright_passed": 0,
|
||||
"failed": 2,
|
||||
"ignored": 0
|
||||
},
|
||||
"evidence": {
|
||||
"path": "docs/epic-1-completion/evidence/runtime-red.txt",
|
||||
"sha256": "cc54891451ee8bdcd3a55d9edfb05d567bb347c88d370f672a3616c34ec909da"
|
||||
},
|
||||
"raw_log_sha256": "7de6d2c533345fbd1c8413157c96cf56d157625d50b958f90cb1d21f502da0b5",
|
||||
"observation_kind": "baseline with versioned test diff; not a clean implementation revision",
|
||||
"notes": "Production source = baseline; regression test diff versioned separately. Build cache isolated from main checkout.",
|
||||
"test_diff": {
|
||||
"path": "docs/epic-1-completion/evidence/runtime-red.patch",
|
||||
"sha256": "68b290aeeade258b9ae4a9df738c0f6665e16a28845d174364abf9893122cc79"
|
||||
},
|
||||
"source_sha256": {
|
||||
"crates/crank-runtime/tests/execution_certainty.rs": "bc6b72ec2b07bb7d784ebdbeac9de4c3b1426ec0a83c7495005be7203710ef9e"
|
||||
},
|
||||
"build_cache": "isolated per-checkout target",
|
||||
"configuration_revision": "c172e3cfa235ab9e91b5996e9cab506fabb889f8",
|
||||
"configuration": [
|
||||
{
|
||||
"path": "Cargo.toml",
|
||||
"sha256": "f67b97bb1e0bc79204ee17330c3ac773afd94629a033860fe770bee75fa1f451"
|
||||
},
|
||||
{
|
||||
"path": "Cargo.lock",
|
||||
"sha256": "f4fe785c08b9ae4007cab0246b163108ef3525d8c87e81cf9dd4c5b801ed562a"
|
||||
},
|
||||
{
|
||||
"path": "justfile",
|
||||
"sha256": "4f7af4b6181efb7dc2219608eef4c1cb179ea225751151e9b50fe20ec58164ec"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/package-lock.json",
|
||||
"sha256": "b60165a1de830edc0d7cd0ee5e7ca83d5cc66b97c05086f4d34eacd2699d4dce"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/playwright.config.js",
|
||||
"sha256": "67b86c341d98cc5bdd41e04d9c8f456fa3ef05438f41a9ee82450e31d5226775"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/scripts/playwright-stack.sh",
|
||||
"sha256": "bd562d8cd437e326de2a2d0ff4888d2674f5d934e3d757967a9a34bd01aff420"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "agent-red",
|
||||
"baseline_commit": "c172e3cfa235ab9e91b5996e9cab506fabb889f8",
|
||||
"command": "cargo test -p admin-api --test integration agent_catalog_edit -- --test-threads=1 --nocapture",
|
||||
"exit_code": 101,
|
||||
"status": "fail",
|
||||
"counts": {
|
||||
"passed": 0,
|
||||
"rust_passed": 0,
|
||||
"tooling_passed": 0,
|
||||
"playwright_passed": 0,
|
||||
"failed": 8,
|
||||
"ignored": 0
|
||||
},
|
||||
"evidence": {
|
||||
"path": "docs/epic-1-completion/evidence/agent-red.txt",
|
||||
"sha256": "b62f9e6e10ef7b09228d5f4b035e9569351835c2e39703e436abcb9c8095b419"
|
||||
},
|
||||
"raw_log_sha256": "23b2889d626dec3ed5ff3b9d51d643f62aff01d25ac203189f349cca08aea438",
|
||||
"observation_kind": "baseline with versioned test diff; not a clean implementation revision",
|
||||
"notes": "Production source = baseline; regression test diff versioned separately. Build cache isolated from main checkout.",
|
||||
"test_diff": {
|
||||
"path": "docs/epic-1-completion/evidence/agent-red.patch",
|
||||
"sha256": "5e5a99b3c0dda44a7228c7f5f82d80e0a362806dd03dc7c1baed5edb79ee45af"
|
||||
},
|
||||
"source_sha256": {
|
||||
"apps/admin-api/tests/integration/agent_catalog_edit.rs": "a417c1342742393fd21d1ae88b4322fc21dbb9ff1adbc84a47d9df221c1081d3",
|
||||
"apps/admin-api/tests/integration.rs": "713b232d59c52c33f0d36c432718841ebf2f64e8226f5f25ae3c19a7f2d73b1b"
|
||||
},
|
||||
"build_cache": "isolated per-checkout target",
|
||||
"behavioral_red_notes": [
|
||||
{
|
||||
"test": "published_agent_first_edit_forks_one_draft_and_keeps_published_snapshot",
|
||||
"line": 227,
|
||||
"classification": "behavioral",
|
||||
"actual": "HTTP 409 agent_stale_revision",
|
||||
"expected": "HTTP 200 with forked Draft v2"
|
||||
},
|
||||
{
|
||||
"test": "rejected_invalid_policy_leaves_no_durable_draft",
|
||||
"line": 144,
|
||||
"classification": "behavioral",
|
||||
"actual": "current_draft_version=2",
|
||||
"expected": "current_draft_version=1 (no durable draft)"
|
||||
},
|
||||
{
|
||||
"test": "rejected_unpublished_operation_leaves_no_durable_draft",
|
||||
"line": 144,
|
||||
"classification": "behavioral",
|
||||
"actual": "current_draft_version=2",
|
||||
"expected": "current_draft_version=1 (no durable draft)"
|
||||
},
|
||||
{
|
||||
"test": "rejected_archived_operation_leaves_no_durable_draft",
|
||||
"line": 144,
|
||||
"classification": "behavioral",
|
||||
"actual": "current_draft_version=2",
|
||||
"expected": "current_draft_version=1 (no durable draft)"
|
||||
},
|
||||
{
|
||||
"test": "rejected_foreign_operation_leaves_no_durable_draft",
|
||||
"line": 144,
|
||||
"classification": "behavioral",
|
||||
"actual": "current_draft_version=2",
|
||||
"expected": "current_draft_version=1 (no durable draft)"
|
||||
},
|
||||
{
|
||||
"test": "concurrent_first_edits_with_same_etag_have_one_winner",
|
||||
"line": 632,
|
||||
"classification": "behavioral",
|
||||
"actual": "successes=0; results=[400 validation_error, 409 agent_stale_revision]",
|
||||
"expected": "exactly one 2xx winner and one 409 conflict on original ETag"
|
||||
},
|
||||
{
|
||||
"test": "first_edit_after_operation_archive_leaves_no_durable_draft",
|
||||
"line": 144,
|
||||
"classification": "behavioral",
|
||||
"actual": "current_draft_version=2",
|
||||
"expected": "current_draft_version=1 (no durable draft)"
|
||||
},
|
||||
{
|
||||
"test": "first_edit_rejects_when_operation_archives_during_save",
|
||||
"line": 144,
|
||||
"classification": "behavioral",
|
||||
"actual": "current_draft_version=2 (independent-pool lock fixture reached the durable oracle)",
|
||||
"expected": "current_draft_version=1 (no durable draft)"
|
||||
}
|
||||
],
|
||||
"behavioral_failures": 8,
|
||||
"fixture_failures": 0,
|
||||
"configuration_revision": "c172e3cfa235ab9e91b5996e9cab506fabb889f8",
|
||||
"configuration": [
|
||||
{
|
||||
"path": "Cargo.toml",
|
||||
"sha256": "f67b97bb1e0bc79204ee17330c3ac773afd94629a033860fe770bee75fa1f451"
|
||||
},
|
||||
{
|
||||
"path": "Cargo.lock",
|
||||
"sha256": "f4fe785c08b9ae4007cab0246b163108ef3525d8c87e81cf9dd4c5b801ed562a"
|
||||
},
|
||||
{
|
||||
"path": "justfile",
|
||||
"sha256": "4f7af4b6181efb7dc2219608eef4c1cb179ea225751151e9b50fe20ec58164ec"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/package-lock.json",
|
||||
"sha256": "b60165a1de830edc0d7cd0ee5e7ca83d5cc66b97c05086f4d34eacd2699d4dce"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/playwright.config.js",
|
||||
"sha256": "67b86c341d98cc5bdd41e04d9c8f456fa3ef05438f41a9ee82450e31d5226775"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/scripts/playwright-stack.sh",
|
||||
"sha256": "bd562d8cd437e326de2a2d0ff4888d2674f5d934e3d757967a9a34bd01aff420"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "scanner-red",
|
||||
"baseline_commit": "c172e3cfa235ab9e91b5996e9cab506fabb889f8",
|
||||
"command": "python3 -m unittest discover -s tests/unit -p test_check_rust_code_health.py",
|
||||
"exit_code": 1,
|
||||
"status": "fail",
|
||||
"counts": {
|
||||
"passed": 3,
|
||||
"rust_passed": 0,
|
||||
"tooling_passed": 3,
|
||||
"playwright_passed": 0,
|
||||
"failed": 2,
|
||||
"ignored": 0,
|
||||
"total": 5,
|
||||
"errors": 0,
|
||||
"skipped": 0
|
||||
},
|
||||
"evidence": {
|
||||
"path": "docs/epic-1-completion/evidence/scanner-red.txt",
|
||||
"sha256": "175fe58c87ce9994af49e03060373f8a4a9aeea9e1893aa327635a0e8354268a"
|
||||
},
|
||||
"raw_log_sha256": "8356f422b61fc717429a87bb143d820df92d5f4c0c813d13eaec69f8e8ab89cb",
|
||||
"observation_kind": "baseline with versioned test diff; not a clean implementation revision",
|
||||
"notes": "Production source = baseline; regression test diff versioned separately. Build cache isolated from main checkout.",
|
||||
"test_diff": {
|
||||
"path": "docs/epic-1-completion/evidence/scanner-red.patch",
|
||||
"sha256": "34fcccc801eb79de4d54aa9f06f5b3c53b6a3eada3b176920f2273c9ea4197a8"
|
||||
},
|
||||
"source_sha256": {
|
||||
"tests/unit/test_check_rust_code_health.py": "058f8200a6b3c6dcd53611ba871efc9acb13dfcefceb43d96b1f713cb44a4fd1"
|
||||
},
|
||||
"build_cache": "isolated per-checkout target",
|
||||
"configuration_revision": "c172e3cfa235ab9e91b5996e9cab506fabb889f8",
|
||||
"configuration": [
|
||||
{
|
||||
"path": "Cargo.toml",
|
||||
"sha256": "f67b97bb1e0bc79204ee17330c3ac773afd94629a033860fe770bee75fa1f451"
|
||||
},
|
||||
{
|
||||
"path": "Cargo.lock",
|
||||
"sha256": "f4fe785c08b9ae4007cab0246b163108ef3525d8c87e81cf9dd4c5b801ed562a"
|
||||
},
|
||||
{
|
||||
"path": "justfile",
|
||||
"sha256": "4f7af4b6181efb7dc2219608eef4c1cb179ea225751151e9b50fe20ec58164ec"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/package-lock.json",
|
||||
"sha256": "b60165a1de830edc0d7cd0ee5e7ca83d5cc66b97c05086f4d34eacd2699d4dce"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/playwright.config.js",
|
||||
"sha256": "67b86c341d98cc5bdd41e04d9c8f456fa3ef05438f41a9ee82450e31d5226775"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/scripts/playwright-stack.sh",
|
||||
"sha256": "bd562d8cd437e326de2a2d0ff4888d2674f5d934e3d757967a9a34bd01aff420"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "sqlx-red",
|
||||
"baseline_commit": "1b9f7f66f9f89dcfed8d4d2efa71986063741ca0",
|
||||
"command": "cargo test --manifest-path vendor/sqlx-core/Cargo.toml --locked --lib -- pool::inner::tests",
|
||||
"exit_code": 101,
|
||||
"status": "fail",
|
||||
"counts": {
|
||||
"passed": 1,
|
||||
"rust_passed": 1,
|
||||
"tooling_passed": 0,
|
||||
"playwright_passed": 0,
|
||||
"failed": 2,
|
||||
"ignored": 0
|
||||
},
|
||||
"evidence": {
|
||||
"path": "docs/epic-1-completion/evidence/sqlx-red.txt",
|
||||
"sha256": "30ee7534d4940e331e75dfd6a9aa4af72f057a0917ee429030a5dfbba37c96e7"
|
||||
},
|
||||
"raw_log_sha256": "8a66a61d93ca1662c594fa257a3a6169ac104dcbbe08d127d2b92275a15a6f83",
|
||||
"observation_kind": "baseline with versioned test diff; not a clean implementation revision",
|
||||
"source_archive_sha256": "05b44e85bf579a8eeb4ceaa77a3a523baf2bf0e9bac7e40f405d537b5d2d5ccb",
|
||||
"intermediate_inner_sha256": "806f6e86622e7d1a8bc0a8b85563e61ec7920bb2bd0afcfc65866cb88d7f2352",
|
||||
"notes": "Exact intermediate test seams preserve upstream ordering and unbounded batch. Forced interleaving uses real ArrayQueue and two barriers; no observed live MAX claim.",
|
||||
"artifacts": [
|
||||
{
|
||||
"path": "docs/epic-1-completion/evidence/sqlx-red.patch",
|
||||
"sha256": "940f4cff4633a32630fd30c4fc1d7c51772e24e2faa2bd4c05c46665d1ac5301"
|
||||
},
|
||||
{
|
||||
"path": "docs/epic-1-completion/evidence/sqlx-accepted.patch",
|
||||
"sha256": "050fa5f426dd3a885e4f4931c87fe8751d142d23f0cf5a8b8809530e9c3046f1"
|
||||
}
|
||||
],
|
||||
"configuration_revision": "1b9f7f66f9f89dcfed8d4d2efa71986063741ca0",
|
||||
"configuration": [
|
||||
{
|
||||
"path": "Cargo.toml",
|
||||
"sha256": "f67b97bb1e0bc79204ee17330c3ac773afd94629a033860fe770bee75fa1f451"
|
||||
},
|
||||
{
|
||||
"path": "Cargo.lock",
|
||||
"sha256": "f4fe785c08b9ae4007cab0246b163108ef3525d8c87e81cf9dd4c5b801ed562a"
|
||||
},
|
||||
{
|
||||
"path": "justfile",
|
||||
"sha256": "4f7af4b6181efb7dc2219608eef4c1cb179ea225751151e9b50fe20ec58164ec"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/package-lock.json",
|
||||
"sha256": "b60165a1de830edc0d7cd0ee5e7ca83d5cc66b97c05086f4d34eacd2699d4dce"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/playwright.config.js",
|
||||
"sha256": "67b86c341d98cc5bdd41e04d9c8f456fa3ef05438f41a9ee82450e31d5226775"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/scripts/playwright-stack.sh",
|
||||
"sha256": "bd562d8cd437e326de2a2d0ff4888d2674f5d934e3d757967a9a34bd01aff420"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "sqlx-clean",
|
||||
"baseline_commit": "c172e3cfa235ab9e91b5996e9cab506fabb889f8",
|
||||
"command": "cargo test --manifest-path vendor/sqlx-core/Cargo.toml --locked --lib",
|
||||
"exit_code": 0,
|
||||
"status": "pass",
|
||||
"counts": {
|
||||
"passed": 5,
|
||||
"rust_passed": 5,
|
||||
"tooling_passed": 0,
|
||||
"playwright_passed": 0,
|
||||
"failed": 0,
|
||||
"ignored": 0
|
||||
},
|
||||
"evidence": {
|
||||
"path": "docs/epic-1-completion/evidence/sqlx-clean.txt",
|
||||
"sha256": "46f0f3945e887159de72ed93d78367d0b66c23613df880e3095f8fbfe4b7a9c4"
|
||||
},
|
||||
"raw_log_sha256": "d2cbb5fec00042d08c18d05aa33e19833d69325046a6b2bc59c66ae99aadb9e1",
|
||||
"implementation_revision": "d7fa0862c717b1874df58b6dbe2329cb66faaaeb",
|
||||
"worktree_state": "clean at start and end",
|
||||
"clean_at_start": true,
|
||||
"clean_at_end": true,
|
||||
"build_cache": "isolated cargo home and target",
|
||||
"source_sha256": {
|
||||
"vendor/sqlx-core/src/pool/inner.rs": "a1aae62b535276aa91695861f18d7fa9ea098a7388f621d89f359b8e403ebbf6"
|
||||
},
|
||||
"source_archive_sha256": "05b44e85bf579a8eeb4ceaa77a3a523baf2bf0e9bac7e40f405d537b5d2d5ccb",
|
||||
"licenses": [
|
||||
{
|
||||
"path": "vendor/sqlx-core/LICENSE-MIT",
|
||||
"upstream": "https://raw.githubusercontent.com/transact-rs/sqlx/v0.9.0/LICENSE-MIT",
|
||||
"sha256": "5abbdd842310c8f1650fcde3a5a51a3e09412b9e5a6eea87519e0db9e32b339d"
|
||||
},
|
||||
{
|
||||
"path": "vendor/sqlx-core/LICENSE-APACHE",
|
||||
"upstream": "https://raw.githubusercontent.com/transact-rs/sqlx/v0.9.0/LICENSE-APACHE",
|
||||
"sha256": "c8f5453612253e8ea8bad241617fe74c4a6d5d592ba64ff881668c211b50ac99"
|
||||
}
|
||||
],
|
||||
"configuration_revision": "d7fa0862c717b1874df58b6dbe2329cb66faaaeb",
|
||||
"configuration": [
|
||||
{
|
||||
"path": "Cargo.toml",
|
||||
"sha256": "3b9045aa880d6e9e8463c90dde089407d12d1a141af82c78169b71b96e644512"
|
||||
},
|
||||
{
|
||||
"path": "Cargo.lock",
|
||||
"sha256": "afe994e31bcf1e595ce5a82e5cefbd9ebc3ebe372b929071163d0fe370c3b12b"
|
||||
},
|
||||
{
|
||||
"path": "justfile",
|
||||
"sha256": "4f7af4b6181efb7dc2219608eef4c1cb179ea225751151e9b50fe20ec58164ec"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/package-lock.json",
|
||||
"sha256": "b60165a1de830edc0d7cd0ee5e7ca83d5cc66b97c05086f4d34eacd2699d4dce"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/playwright.config.js",
|
||||
"sha256": "67b86c341d98cc5bdd41e04d9c8f456fa3ef05438f41a9ee82450e31d5226775"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/scripts/playwright-stack.sh",
|
||||
"sha256": "bd562d8cd437e326de2a2d0ff4888d2674f5d934e3d757967a9a34bd01aff420"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "community-scope-red",
|
||||
"baseline_commit": "d7fa0862c717b1874df58b6dbe2329cb66faaaeb",
|
||||
"command": "python3 -m unittest discover -s tests/unit -p 'test_check_community_scope.py' -v",
|
||||
"exit_code": 1,
|
||||
"status": "fail",
|
||||
"counts": {
|
||||
"passed": 21,
|
||||
"rust_passed": 0,
|
||||
"tooling_passed": 21,
|
||||
"playwright_passed": 0,
|
||||
"failed": 1,
|
||||
"ignored": 0
|
||||
},
|
||||
"evidence": {
|
||||
"path": "docs/epic-1-completion/evidence/community-scope-red.txt",
|
||||
"sha256": "35dba5178d5ee6d39aa64953908d09ca072518d1952e38c7301f94fc65393d16"
|
||||
},
|
||||
"raw_log_sha256": "74103832915aecdb27c2e651585c6374092dfcc04545b2a46b178fea292e9df1",
|
||||
"observation_kind": "baseline with versioned test diff; not a clean implementation revision",
|
||||
"test_diff": {
|
||||
"path": "tests/unit/test_check_community_scope.py",
|
||||
"revision": "4a4922495b07b69ef8d405c74adc14d7383b5001",
|
||||
"sha256": "c81c1eecc53606446cb64a5974902e119f59bc2948e99de7ad7c90d7d9d9f12f",
|
||||
"from_revision": "d7fa0862c717b1874df58b6dbe2329cb66faaaeb",
|
||||
"diff_sha256": "ef734868a4ac18f025bdcb187342107691c5ab042f088cccd6a5d1b493e250f6",
|
||||
"reconstruct_command": "git diff d7fa0862c717b1874df58b6dbe2329cb66faaaeb 4a4922495b07b69ef8d405c74adc14d7383b5001 -- tests/unit/test_check_community_scope.py"
|
||||
},
|
||||
"notes": "Checker production source at baseline; exact added test source is versioned in the indicated Git revision; test diff reconstructs from the two recorded revisions.",
|
||||
"configuration_revision": "d7fa0862c717b1874df58b6dbe2329cb66faaaeb",
|
||||
"configuration": [
|
||||
{
|
||||
"path": "Cargo.toml",
|
||||
"sha256": "3b9045aa880d6e9e8463c90dde089407d12d1a141af82c78169b71b96e644512"
|
||||
},
|
||||
{
|
||||
"path": "Cargo.lock",
|
||||
"sha256": "afe994e31bcf1e595ce5a82e5cefbd9ebc3ebe372b929071163d0fe370c3b12b"
|
||||
},
|
||||
{
|
||||
"path": "justfile",
|
||||
"sha256": "4f7af4b6181efb7dc2219608eef4c1cb179ea225751151e9b50fe20ec58164ec"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/package-lock.json",
|
||||
"sha256": "b60165a1de830edc0d7cd0ee5e7ca83d5cc66b97c05086f4d34eacd2699d4dce"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/playwright.config.js",
|
||||
"sha256": "67b86c341d98cc5bdd41e04d9c8f456fa3ef05438f41a9ee82450e31d5226775"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/scripts/playwright-stack.sh",
|
||||
"sha256": "bd562d8cd437e326de2a2d0ff4888d2674f5d934e3d757967a9a34bd01aff420"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "workspace-startup-collision",
|
||||
"baseline_commit": "c172e3cfa235ab9e91b5996e9cab506fabb889f8",
|
||||
"command": "just verify",
|
||||
"exit_code": 101,
|
||||
"status": "fail",
|
||||
"counts": {
|
||||
"passed": 199,
|
||||
"rust_passed": 43,
|
||||
"tooling_passed": 156,
|
||||
"playwright_passed": 0,
|
||||
"failed": 2,
|
||||
"ignored": 0
|
||||
},
|
||||
"evidence": {
|
||||
"path": "docs/epic-1-completion/evidence/workspace-startup-collision.txt",
|
||||
"sha256": "807120303d8fdefbdb23b9c29fc7b8d22698c7a63fac39ceabe83193eb75102f"
|
||||
},
|
||||
"raw_log_sha256": "78bf9a95fb39abdabc5eaa87e044977b449a34d7bdc4b634dadf74ac9a242fe0",
|
||||
"implementation_revision": "1b9f7f66f9f89dcfed8d4d2efa71986063741ca0",
|
||||
"worktree_state": "clean at start and end",
|
||||
"notes": "При параллельном UI stack startup tests не могли занять metrics bind 9464; 4 startup tests passed, 2 failed. После остановки stack полный gate повторён отдельно. Не является успешным gate.",
|
||||
"configuration_revision": "1b9f7f66f9f89dcfed8d4d2efa71986063741ca0",
|
||||
"configuration": [
|
||||
{
|
||||
"path": "Cargo.toml",
|
||||
"sha256": "f67b97bb1e0bc79204ee17330c3ac773afd94629a033860fe770bee75fa1f451"
|
||||
},
|
||||
{
|
||||
"path": "Cargo.lock",
|
||||
"sha256": "f4fe785c08b9ae4007cab0246b163108ef3525d8c87e81cf9dd4c5b801ed562a"
|
||||
},
|
||||
{
|
||||
"path": "justfile",
|
||||
"sha256": "4f7af4b6181efb7dc2219608eef4c1cb179ea225751151e9b50fe20ec58164ec"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/package-lock.json",
|
||||
"sha256": "b60165a1de830edc0d7cd0ee5e7ca83d5cc66b97c05086f4d34eacd2699d4dce"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/playwright.config.js",
|
||||
"sha256": "67b86c341d98cc5bdd41e04d9c8f456fa3ef05438f41a9ee82450e31d5226775"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/scripts/playwright-stack.sh",
|
||||
"sha256": "bd562d8cd437e326de2a2d0ff4888d2674f5d934e3d757967a9a34bd01aff420"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "workspace-sqlx-hang",
|
||||
"baseline_commit": "c172e3cfa235ab9e91b5996e9cab506fabb889f8",
|
||||
"command": "just verify",
|
||||
"exit_code": 101,
|
||||
"status": "interrupted",
|
||||
"counts": {
|
||||
"passed": 202,
|
||||
"rust_passed": 46,
|
||||
"tooling_passed": 156,
|
||||
"playwright_passed": 0,
|
||||
"failed": 0,
|
||||
"ignored": 0
|
||||
},
|
||||
"evidence": {
|
||||
"path": "docs/epic-1-completion/evidence/workspace-sqlx-hang.txt",
|
||||
"sha256": "d3a48ee80a94ed25ee9b7f9a586601de4b888be08720848a520cdda77a7996eb"
|
||||
},
|
||||
"raw_log_sha256": "31213e65d92afb68d399cb63cfc67b2bf17b43ef1fa0010d69c5729ab8c73816",
|
||||
"implementation_revision": "1b9f7f66f9f89dcfed8d4d2efa71986063741ca0",
|
||||
"worktree_state": "clean at start and end",
|
||||
"notes": "Прерванный sustained SQLx maintenance busy loop, без UI stack. IP sampling повторно указывает на maintenance/try_acquire/release; MAX counter не наблюдался. Это не PASS; dependency patch проверяется отдельно.",
|
||||
"configuration_revision": "1b9f7f66f9f89dcfed8d4d2efa71986063741ca0",
|
||||
"configuration": [
|
||||
{
|
||||
"path": "Cargo.toml",
|
||||
"sha256": "f67b97bb1e0bc79204ee17330c3ac773afd94629a033860fe770bee75fa1f451"
|
||||
},
|
||||
{
|
||||
"path": "Cargo.lock",
|
||||
"sha256": "f4fe785c08b9ae4007cab0246b163108ef3525d8c87e81cf9dd4c5b801ed562a"
|
||||
},
|
||||
{
|
||||
"path": "justfile",
|
||||
"sha256": "4f7af4b6181efb7dc2219608eef4c1cb179ea225751151e9b50fe20ec58164ec"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/package-lock.json",
|
||||
"sha256": "b60165a1de830edc0d7cd0ee5e7ca83d5cc66b97c05086f4d34eacd2699d4dce"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/playwright.config.js",
|
||||
"sha256": "67b86c341d98cc5bdd41e04d9c8f456fa3ef05438f41a9ee82450e31d5226775"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/scripts/playwright-stack.sh",
|
||||
"sha256": "bd562d8cd437e326de2a2d0ff4888d2674f5d934e3d757967a9a34bd01aff420"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "workspace-vendor-scope-fail",
|
||||
"baseline_commit": "c172e3cfa235ab9e91b5996e9cab506fabb889f8",
|
||||
"command": "just verify",
|
||||
"exit_code": 1,
|
||||
"status": "fail",
|
||||
"counts": {
|
||||
"passed": 156,
|
||||
"rust_passed": 0,
|
||||
"tooling_passed": 156,
|
||||
"playwright_passed": 0,
|
||||
"failed": 0,
|
||||
"ignored": 0
|
||||
},
|
||||
"evidence": {
|
||||
"path": "docs/epic-1-completion/evidence/workspace-vendor-scope-fail.txt",
|
||||
"sha256": "7f78c2269f8772ecccec8acb5f2719bc3a53658be3832b58ff18402021bf5f89"
|
||||
},
|
||||
"raw_log_sha256": "ce8d5494dee8b0efa46e8b22efe95138322399e6d2c9f0b9d8be8466a3b1ec74",
|
||||
"implementation_revision": "d7fa0862c717b1874df58b6dbe2329cb66faaaeb",
|
||||
"worktree_state": "clean at start and end",
|
||||
"notes": "Community scanner rejected upstream SQLx comments/license; scoped dependency exclusion subsequently verified. This attempt is FAIL.",
|
||||
"configuration_revision": "d7fa0862c717b1874df58b6dbe2329cb66faaaeb",
|
||||
"configuration": [
|
||||
{
|
||||
"path": "Cargo.toml",
|
||||
"sha256": "3b9045aa880d6e9e8463c90dde089407d12d1a141af82c78169b71b96e644512"
|
||||
},
|
||||
{
|
||||
"path": "Cargo.lock",
|
||||
"sha256": "afe994e31bcf1e595ce5a82e5cefbd9ebc3ebe372b929071163d0fe370c3b12b"
|
||||
},
|
||||
{
|
||||
"path": "justfile",
|
||||
"sha256": "4f7af4b6181efb7dc2219608eef4c1cb179ea225751151e9b50fe20ec58164ec"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/package-lock.json",
|
||||
"sha256": "b60165a1de830edc0d7cd0ee5e7ca83d5cc66b97c05086f4d34eacd2699d4dce"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/playwright.config.js",
|
||||
"sha256": "67b86c341d98cc5bdd41e04d9c8f456fa3ef05438f41a9ee82450e31d5226775"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/scripts/playwright-stack.sh",
|
||||
"sha256": "bd562d8cd437e326de2a2d0ff4888d2674f5d934e3d757967a9a34bd01aff420"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "workspace-runner-interrupted",
|
||||
"baseline_commit": "c172e3cfa235ab9e91b5996e9cab506fabb889f8",
|
||||
"command": "just verify",
|
||||
"exit_code": 143,
|
||||
"status": "interrupted",
|
||||
"counts": {
|
||||
"passed": 159,
|
||||
"rust_passed": 0,
|
||||
"tooling_passed": 159,
|
||||
"playwright_passed": 0,
|
||||
"failed": 0,
|
||||
"ignored": 0
|
||||
},
|
||||
"evidence": {
|
||||
"path": "docs/epic-1-completion/evidence/workspace-runner-interrupted.txt",
|
||||
"sha256": "e401fae4ff2eb48f1dc70ec1f249f8894710ee229be9d7237f826fac4b0abfb0"
|
||||
},
|
||||
"raw_log_sha256": "7dd0997371123de20c93d9f1588ad9a5adeb7954990c0c40ea8e6cc556ec96a1",
|
||||
"implementation_revision": "4a4922495b07b69ef8d405c74adc14d7383b5001",
|
||||
"worktree_state": "clean at start and end",
|
||||
"notes": "Execution session ended with SIGTERM before runner emitted final metadata; sender not established. No test assertion failure reported.",
|
||||
"configuration_revision": "4a4922495b07b69ef8d405c74adc14d7383b5001",
|
||||
"configuration": [
|
||||
{
|
||||
"path": "Cargo.toml",
|
||||
"sha256": "3b9045aa880d6e9e8463c90dde089407d12d1a141af82c78169b71b96e644512"
|
||||
},
|
||||
{
|
||||
"path": "Cargo.lock",
|
||||
"sha256": "afe994e31bcf1e595ce5a82e5cefbd9ebc3ebe372b929071163d0fe370c3b12b"
|
||||
},
|
||||
{
|
||||
"path": "justfile",
|
||||
"sha256": "4f7af4b6181efb7dc2219608eef4c1cb179ea225751151e9b50fe20ec58164ec"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/package-lock.json",
|
||||
"sha256": "b60165a1de830edc0d7cd0ee5e7ca83d5cc66b97c05086f4d34eacd2699d4dce"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/playwright.config.js",
|
||||
"sha256": "67b86c341d98cc5bdd41e04d9c8f456fa3ef05438f41a9ee82450e31d5226775"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/scripts/playwright-stack.sh",
|
||||
"sha256": "bd562d8cd437e326de2a2d0ff4888d2674f5d934e3d757967a9a34bd01aff420"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "real-stack-flaky-playwright",
|
||||
"baseline_commit": "c172e3cfa235ab9e91b5996e9cab506fabb889f8",
|
||||
"command": "PLAYWRIGHT_SKIP_WEB_SERVER=1 CI= npm run e2e -- tests/e2e/onboarding.spec.js tests/e2e/operation-lifecycle.spec.js tests/e2e/agents.spec.js --workers=1",
|
||||
"exit_code": 0,
|
||||
"status": "flaky",
|
||||
"counts": {
|
||||
"passed": 16,
|
||||
"rust_passed": 0,
|
||||
"tooling_passed": 0,
|
||||
"playwright_passed": 16,
|
||||
"failed": 0,
|
||||
"ignored": 0,
|
||||
"flaky": 1,
|
||||
"failed_attempts": 1
|
||||
},
|
||||
"evidence": {
|
||||
"path": "docs/epic-1-completion/evidence/real-stack-flaky-playwright.txt",
|
||||
"sha256": "61c75bbd722b5cef295b61700087836de6de5287730ca5cab6ca575aaab88d5c"
|
||||
},
|
||||
"raw_log_sha256": "26df7bf48f39deafad4906a07426c96204c3878adb0e9c235dcb6e7d3ea0d77e",
|
||||
"implementation_revision": "4a4922495b07b69ef8d405c74adc14d7383b5001",
|
||||
"worktree_state": "clean at start and end",
|
||||
"notes": "Unconditional trigger click closed an auto-opened checklist; first attempt timed out, configured retry passed. This run is FLAKY, not PASS.",
|
||||
"configured_retries": 1,
|
||||
"retries_observed": 1,
|
||||
"working_directory": "apps/ui",
|
||||
"configuration_revision": "4a4922495b07b69ef8d405c74adc14d7383b5001",
|
||||
"configuration": [
|
||||
{
|
||||
"path": "Cargo.toml",
|
||||
"sha256": "3b9045aa880d6e9e8463c90dde089407d12d1a141af82c78169b71b96e644512"
|
||||
},
|
||||
{
|
||||
"path": "Cargo.lock",
|
||||
"sha256": "afe994e31bcf1e595ce5a82e5cefbd9ebc3ebe372b929071163d0fe370c3b12b"
|
||||
},
|
||||
{
|
||||
"path": "justfile",
|
||||
"sha256": "4f7af4b6181efb7dc2219608eef4c1cb179ea225751151e9b50fe20ec58164ec"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/package-lock.json",
|
||||
"sha256": "b60165a1de830edc0d7cd0ee5e7ca83d5cc66b97c05086f4d34eacd2699d4dce"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/playwright.config.js",
|
||||
"sha256": "67b86c341d98cc5bdd41e04d9c8f456fa3ef05438f41a9ee82450e31d5226775"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/scripts/playwright-stack.sh",
|
||||
"sha256": "bd562d8cd437e326de2a2d0ff4888d2674f5d934e3d757967a9a34bd01aff420"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "workspace-verify",
|
||||
"baseline_commit": "c172e3cfa235ab9e91b5996e9cab506fabb889f8",
|
||||
"command": "just verify",
|
||||
"exit_code": 0,
|
||||
"status": "pass",
|
||||
"counts": {
|
||||
"passed": 1178,
|
||||
"rust_passed": 1019,
|
||||
"tooling_passed": 159,
|
||||
"playwright_passed": 0,
|
||||
"failed": 0,
|
||||
"ignored": 1
|
||||
},
|
||||
"evidence": {
|
||||
"path": "docs/epic-1-completion/evidence/workspace-verify.txt",
|
||||
"sha256": "0342aec5b0e760f5f327fe1e1f91a08b2f20b949e495bb99ca62201c314bb398"
|
||||
},
|
||||
"raw_log_sha256": "ece242050ab717861b84c6babcbc7bda02b034bdfd57fb858f7ece017d9132ef",
|
||||
"implementation_revision": "4a4922495b07b69ef8d405c74adc14d7383b5001",
|
||||
"worktree_state": "clean at start and end",
|
||||
"ignored_cases": [
|
||||
{
|
||||
"test": "integration::observability::production_size_invocation_history_queries_stay_bounded",
|
||||
"reason": "production-size query-plan evidence: inserts 1,000,000 invocation_logs rows"
|
||||
}
|
||||
],
|
||||
"clean_at_start": true,
|
||||
"clean_at_end": true,
|
||||
"same_revision_at_end": true,
|
||||
"stdout_capture": "pipe",
|
||||
"other_stack_running": false,
|
||||
"configuration_revision": "4a4922495b07b69ef8d405c74adc14d7383b5001",
|
||||
"configuration": [
|
||||
{
|
||||
"path": "Cargo.toml",
|
||||
"sha256": "3b9045aa880d6e9e8463c90dde089407d12d1a141af82c78169b71b96e644512"
|
||||
},
|
||||
{
|
||||
"path": "Cargo.lock",
|
||||
"sha256": "afe994e31bcf1e595ce5a82e5cefbd9ebc3ebe372b929071163d0fe370c3b12b"
|
||||
},
|
||||
{
|
||||
"path": "justfile",
|
||||
"sha256": "4f7af4b6181efb7dc2219608eef4c1cb179ea225751151e9b50fe20ec58164ec"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/package-lock.json",
|
||||
"sha256": "b60165a1de830edc0d7cd0ee5e7ca83d5cc66b97c05086f4d34eacd2699d4dce"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/playwright.config.js",
|
||||
"sha256": "67b86c341d98cc5bdd41e04d9c8f456fa3ef05438f41a9ee82450e31d5226775"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/scripts/playwright-stack.sh",
|
||||
"sha256": "bd562d8cd437e326de2a2d0ff4888d2674f5d934e3d757967a9a34bd01aff420"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "real-stack-final-playwright",
|
||||
"baseline_commit": "c172e3cfa235ab9e91b5996e9cab506fabb889f8",
|
||||
"command": "PLAYWRIGHT_SKIP_WEB_SERVER=1 CI= npm run e2e -- tests/e2e/onboarding.spec.js tests/e2e/operation-lifecycle.spec.js tests/e2e/agents.spec.js --workers=1 --retries=0",
|
||||
"exit_code": 0,
|
||||
"status": "pass",
|
||||
"counts": {
|
||||
"passed": 17,
|
||||
"rust_passed": 0,
|
||||
"tooling_passed": 0,
|
||||
"playwright_passed": 17,
|
||||
"failed": 0,
|
||||
"ignored": 0,
|
||||
"skipped": 0,
|
||||
"flaky": 0
|
||||
},
|
||||
"evidence": {
|
||||
"path": "docs/epic-1-completion/evidence/real-stack-final-playwright.txt",
|
||||
"sha256": "086d8a1ec81184658e92fd18531da8abe294d679c42b80730d9969fa4a77a5ea"
|
||||
},
|
||||
"raw_log_sha256": "4fc020bd91be4d1157e3aa8417a5a342061e10bd2c74f97a7cc11d24dec9da44",
|
||||
"implementation_revision": "9496b19736c275ded2731dae399e04dd9a2fcce2",
|
||||
"worktree_state": "clean at start and end",
|
||||
"notes": "Настоящие PG/Admin/MCP/UI и fixture upstream; часть onboarding recovery cases использует controlled route responses. Реальный first-post-publish edit проверен отдельным browser probe.",
|
||||
"working_directory": "apps/ui",
|
||||
"configured_retries": 0,
|
||||
"retries_observed": 0,
|
||||
"stack_command": "bash apps/ui/scripts/playwright-stack.sh",
|
||||
"configuration_revision": "9496b19736c275ded2731dae399e04dd9a2fcce2",
|
||||
"configuration": [
|
||||
{
|
||||
"path": "Cargo.toml",
|
||||
"sha256": "3b9045aa880d6e9e8463c90dde089407d12d1a141af82c78169b71b96e644512"
|
||||
},
|
||||
{
|
||||
"path": "Cargo.lock",
|
||||
"sha256": "afe994e31bcf1e595ce5a82e5cefbd9ebc3ebe372b929071163d0fe370c3b12b"
|
||||
},
|
||||
{
|
||||
"path": "justfile",
|
||||
"sha256": "4f7af4b6181efb7dc2219608eef4c1cb179ea225751151e9b50fe20ec58164ec"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/package-lock.json",
|
||||
"sha256": "b60165a1de830edc0d7cd0ee5e7ca83d5cc66b97c05086f4d34eacd2699d4dce"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/playwright.config.js",
|
||||
"sha256": "67b86c341d98cc5bdd41e04d9c8f456fa3ef05438f41a9ee82450e31d5226775"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/scripts/playwright-stack.sh",
|
||||
"sha256": "bd562d8cd437e326de2a2d0ff4888d2674f5d934e3d757967a9a34bd01aff420"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "agent-browser-probe",
|
||||
"baseline_commit": "c172e3cfa235ab9e91b5996e9cab506fabb889f8",
|
||||
"implementation_revision": "9496b19736c275ded2731dae399e04dd9a2fcce2",
|
||||
"worktree_state": "clean at start and end",
|
||||
"command": "node docs/epic-1-completion/evidence/agent-probe.cjs",
|
||||
"stack_command": "bash apps/ui/scripts/playwright-stack.sh",
|
||||
"exit_code": 0,
|
||||
"status": "pass",
|
||||
"counts": {
|
||||
"assertions_passed": 5,
|
||||
"assertions_failed": 0
|
||||
},
|
||||
"evidence": {
|
||||
"path": "docs/epic-1-completion/evidence/agent-browser-probe.json",
|
||||
"sha256": "76339bccf74ce9d5a4d67e37bc3a05880dcbec9d3b842bd858d3f9a19f943422"
|
||||
},
|
||||
"configuration_revision": "9496b19736c275ded2731dae399e04dd9a2fcce2",
|
||||
"configuration": [
|
||||
{
|
||||
"path": "Cargo.toml",
|
||||
"sha256": "3b9045aa880d6e9e8463c90dde089407d12d1a141af82c78169b71b96e644512"
|
||||
},
|
||||
{
|
||||
"path": "Cargo.lock",
|
||||
"sha256": "afe994e31bcf1e595ce5a82e5cefbd9ebc3ebe372b929071163d0fe370c3b12b"
|
||||
},
|
||||
{
|
||||
"path": "justfile",
|
||||
"sha256": "4f7af4b6181efb7dc2219608eef4c1cb179ea225751151e9b50fe20ec58164ec"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/package-lock.json",
|
||||
"sha256": "b60165a1de830edc0d7cd0ee5e7ca83d5cc66b97c05086f4d34eacd2699d4dce"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/playwright.config.js",
|
||||
"sha256": "67b86c341d98cc5bdd41e04d9c8f456fa3ef05438f41a9ee82450e31d5226775"
|
||||
},
|
||||
{
|
||||
"path": "apps/ui/scripts/playwright-stack.sh",
|
||||
"sha256": "bd562d8cd437e326de2a2d0ff4888d2674f5d934e3d757967a9a34bd01aff420"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"workspace_source_equivalence": {
|
||||
"from_revision": "4a4922495b07b69ef8d405c74adc14d7383b5001",
|
||||
"to_revision": "9496b19736c275ded2731dae399e04dd9a2fcce2",
|
||||
"changed_paths": [
|
||||
"apps/ui/tests/e2e/onboarding.spec.js"
|
||||
],
|
||||
"disposition": "Only UI E2E test changed; all workspace Rust source, Rust tests, scripts and Cargo configuration exactly match the clean full-gate revision. Final UI runs verify the amended test separately."
|
||||
},
|
||||
"review": {
|
||||
"implementation_revision": "4a4922495b07b69ef8d405c74adc14d7383b5001",
|
||||
"baseline_commit": "c172e3cfa235ab9e91b5996e9cab506fabb889f8",
|
||||
"layers": [
|
||||
"blind-hunter",
|
||||
"edge-case-hunter",
|
||||
"verification-gap"
|
||||
],
|
||||
"findings_triaged": 33,
|
||||
"verification_gap_result": "No verification gaps found.",
|
||||
"deferred": 0,
|
||||
"reviewed_diff_sha256": "86abe5c879abf51069e6a5e1f257eb32765a01be8ab780efdc6fabaf0679ea51",
|
||||
"evidence": {
|
||||
"path": "docs/epic-1-completion/evidence/review-triage.md",
|
||||
"sha256": "ad68f9282a9ed85bc3420b5fabf82e2ba5c7014470834d99ab190b45479e1e47"
|
||||
},
|
||||
"scope_note": "Review source diff completed before the final evidence bundle was written; remaining evidence findings closed by versioned records and independent link/digest/configuration validation."
|
||||
},
|
||||
"post_review_test_fix": {
|
||||
"revision": "9496b19736c275ded2731dae399e04dd9a2fcce2",
|
||||
"path": "apps/ui/tests/e2e/onboarding.spec.js",
|
||||
"sha256": "d9c720e5ffddfc645ff4344dcd9874c954450ea19b43dcf29ebeb9e4a1f6141c",
|
||||
"acceptance": "Lead inspected auto-open/toggle control flow and minimal diff; three covering repeats and final 17 cases passed with retries disabled."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
{
|
||||
"status": "pass",
|
||||
"base_revision": "ca32d3767fb4e0f94c7baf08b7024b1e585937fc",
|
||||
"test_source_sha256": {
|
||||
"apps/ui/tests/e2e/helpers.js": "109fef81b0184484aeed148fe47fb867e96fd8d4a6b695f6b2f5cec6932879ee",
|
||||
"apps/ui/tests/e2e/onboarding.spec.js": "b9172a9186e6adae2e2661543e6a1a289be69fff5e17043817d5ef4f33868436",
|
||||
"apps/ui/tests/e2e/operations.spec.js": "ce19bb50c55e6f00eb643f12fead6ad29c8b6902c417daf3b26b57c1e3fa5968",
|
||||
"apps/ui/tests/e2e/login-readiness.spec.js": "f211cddb8d7d56d2da4b7f645ddde4dac96b85af0bda75eaafba72675df890a4"
|
||||
},
|
||||
"results": {
|
||||
"full_browser_suite": {
|
||||
"startTime": "2026-10-04T23:07:59.039Z",
|
||||
"duration": 160544.748,
|
||||
"expected": 57,
|
||||
"skipped": 0,
|
||||
"unexpected": 0,
|
||||
"flaky": 0
|
||||
},
|
||||
"login_ready_regression": "RED before helper fix; GREEN after helper fix"
|
||||
},
|
||||
"findings": [
|
||||
"Ожидание свойства symbols заменено проверкой целого входа body согласно действующему контракту.",
|
||||
"Setup панели onboarding учитывает её автоматическое открытие.",
|
||||
"Помощник login ожидает штатную загрузку сессии, включая CSRF, прежде чем возвращать управление тесту. Добавлен постоянный тест с задержкой выдачи токена."
|
||||
],
|
||||
"runs": [
|
||||
{
|
||||
"phase": "red",
|
||||
"revision": "ca32d3767fb4e0f94c7baf08b7024b1e585937fc",
|
||||
"command": "PLAYWRIGHT_SKIP_WEB_SERVER=1 CI= npm run e2e -- tests/e2e/operations.spec.js --grep 'imports OpenAPI methods as drafts' --workers=1 --retries=0",
|
||||
"exit_code": 1,
|
||||
"status_before": "",
|
||||
"status_at_run": "",
|
||||
"test_file_sha256": {
|
||||
"apps/ui/tests/e2e/operations.spec.js": "f4b00031d217f8ee1fdfd52550cbef8fa5840d08494ed3c2fed838797c1a65b4",
|
||||
"apps/ui/tests/e2e/onboarding.spec.js": "c83f303d1fe2517b9b55d23e8b1a6d30ee4f6f071ff2310d814213d55a15084b"
|
||||
},
|
||||
"artifact": "./evidence/pr-browser-ci-fix-red-operations.txt",
|
||||
"raw_log_sha256": "df48a470e142d93f7acd3652673ffcaf1fefbdf2754db50b80432dbb3edbe982",
|
||||
"artifact_sha256": "ee4623d670890718b84fb139f63b1b54a96256a4923f3e137d4058fa1f368ff5"
|
||||
},
|
||||
{
|
||||
"phase": "red",
|
||||
"revision": "ca32d3767fb4e0f94c7baf08b7024b1e585937fc",
|
||||
"command": "PLAYWRIGHT_SKIP_WEB_SERVER=1 CI= npm run e2e -- tests/e2e/onboarding.spec.js --grep 'validation, upstream and compatibility' --workers=1 --retries=0",
|
||||
"exit_code": 1,
|
||||
"status_before": "",
|
||||
"status_at_run": "",
|
||||
"test_file_sha256": {
|
||||
"apps/ui/tests/e2e/operations.spec.js": "f4b00031d217f8ee1fdfd52550cbef8fa5840d08494ed3c2fed838797c1a65b4",
|
||||
"apps/ui/tests/e2e/onboarding.spec.js": "c83f303d1fe2517b9b55d23e8b1a6d30ee4f6f071ff2310d814213d55a15084b"
|
||||
},
|
||||
"artifact": "./evidence/pr-browser-ci-fix-red-onboarding.txt",
|
||||
"raw_log_sha256": "c7b53817a7f5d8acf8c82a5b9ff37c2c77b20b3f49fbbfb9360c4fc620ed0fb4",
|
||||
"artifact_sha256": "065e00f26870c16b34d843ffc45c4960aaaae375389a299f98c308828e3164ea"
|
||||
},
|
||||
{
|
||||
"phase": "green",
|
||||
"revision": "ca32d3767fb4e0f94c7baf08b7024b1e585937fc",
|
||||
"command": "PLAYWRIGHT_SKIP_WEB_SERVER=1 CI= npm run e2e -- --workers=1 --retries=0",
|
||||
"exit_code": 1,
|
||||
"status_before": "M apps/ui/tests/e2e/onboarding.spec.js\n M apps/ui/tests/e2e/operations.spec.js",
|
||||
"status_at_run": "M apps/ui/tests/e2e/onboarding.spec.js\n M apps/ui/tests/e2e/operations.spec.js",
|
||||
"test_file_sha256": {
|
||||
"apps/ui/tests/e2e/operations.spec.js": "ce19bb50c55e6f00eb643f12fead6ad29c8b6902c417daf3b26b57c1e3fa5968",
|
||||
"apps/ui/tests/e2e/onboarding.spec.js": "b9172a9186e6adae2e2661543e6a1a289be69fff5e17043817d5ef4f33868436"
|
||||
},
|
||||
"artifact": "./evidence/pr-browser-ci-fix-green-full-suite.txt",
|
||||
"raw_log_sha256": "0f9119ef7bb2764f03d9e72a0906082cc4723e07c8a45dc7aec6518e9c771d48",
|
||||
"artifact_sha256": "1a92992efac9e61bd1a245bae635da9233f6177a7ada7ab9f45f086778e91c24"
|
||||
},
|
||||
{
|
||||
"phase": "red",
|
||||
"revision": "ca32d3767fb4e0f94c7baf08b7024b1e585937fc",
|
||||
"command": "PLAYWRIGHT_SKIP_WEB_SERVER=1 CI= node apps/ui/node_modules/@playwright/test/cli.js test --config state/login-ready-harness/playwright.config.js --workers=1 --retries=0",
|
||||
"exit_code": 1,
|
||||
"status_before": "M apps/ui/tests/e2e/onboarding.spec.js\n M apps/ui/tests/e2e/operations.spec.js",
|
||||
"status_at_run": "M apps/ui/tests/e2e/onboarding.spec.js\n M apps/ui/tests/e2e/operations.spec.js",
|
||||
"file_sha256": {
|
||||
"apps/ui/tests/e2e/helpers.js": "edf98140744f2e7ce54fcb0c2291eb1719b1c8e535883b5d2af6641a10f6c775",
|
||||
"apps/ui/tests/e2e/operations.spec.js": "ce19bb50c55e6f00eb643f12fead6ad29c8b6902c417daf3b26b57c1e3fa5968",
|
||||
"apps/ui/tests/e2e/onboarding.spec.js": "b9172a9186e6adae2e2661543e6a1a289be69fff5e17043817d5ef4f33868436"
|
||||
},
|
||||
"artifact": "./evidence/pr-browser-login-ready-red-harness.txt",
|
||||
"raw_log_sha256": "170b2a8c85e562ad45815bf9c6bf2d408e42b7656ec26013cef7b02a0a78e270",
|
||||
"artifact_sha256": "3fe7ff865726dc14e95dd6a83f568817461b613967a0ea567da72a658c6926a9"
|
||||
},
|
||||
{
|
||||
"phase": "green",
|
||||
"revision": "ca32d3767fb4e0f94c7baf08b7024b1e585937fc",
|
||||
"command": "PLAYWRIGHT_SKIP_WEB_SERVER=1 CI= node apps/ui/node_modules/@playwright/test/cli.js test --config state/login-ready-harness/playwright.config.js --workers=1 --retries=0",
|
||||
"exit_code": 0,
|
||||
"status_before": "M apps/ui/tests/e2e/helpers.js\n M apps/ui/tests/e2e/onboarding.spec.js\n M apps/ui/tests/e2e/operations.spec.js",
|
||||
"status_at_run": "M apps/ui/tests/e2e/helpers.js\n M apps/ui/tests/e2e/onboarding.spec.js\n M apps/ui/tests/e2e/operations.spec.js",
|
||||
"file_sha256": {
|
||||
"apps/ui/tests/e2e/helpers.js": "109fef81b0184484aeed148fe47fb867e96fd8d4a6b695f6b2f5cec6932879ee",
|
||||
"apps/ui/tests/e2e/operations.spec.js": "ce19bb50c55e6f00eb643f12fead6ad29c8b6902c417daf3b26b57c1e3fa5968",
|
||||
"apps/ui/tests/e2e/onboarding.spec.js": "b9172a9186e6adae2e2661543e6a1a289be69fff5e17043817d5ef4f33868436"
|
||||
},
|
||||
"artifact": "./evidence/pr-browser-login-ready-green-harness.txt",
|
||||
"raw_log_sha256": "3f16b4729ffce77bb6d37583c61276117e2da63f6b5dbfca4535293553ca75cc",
|
||||
"artifact_sha256": "3f16b4729ffce77bb6d37583c61276117e2da63f6b5dbfca4535293553ca75cc"
|
||||
},
|
||||
{
|
||||
"revision": "ca32d3767fb4e0f94c7baf08b7024b1e585937fc",
|
||||
"command": "PLAYWRIGHT_SKIP_WEB_SERVER=1 CI= npm run e2e -- --workers=1 --retries=0",
|
||||
"exit_code": 0,
|
||||
"status_before": "M apps/ui/tests/e2e/helpers.js\n M apps/ui/tests/e2e/onboarding.spec.js\n M apps/ui/tests/e2e/operations.spec.js\n?? apps/ui/tests/e2e/login-readiness.spec.js",
|
||||
"status_at_run": "M apps/ui/tests/e2e/helpers.js\n M apps/ui/tests/e2e/onboarding.spec.js\n M apps/ui/tests/e2e/operations.spec.js\n?? apps/ui/tests/e2e/login-readiness.spec.js",
|
||||
"file_sha256": {
|
||||
"apps/ui/tests/e2e/helpers.js": "109fef81b0184484aeed148fe47fb867e96fd8d4a6b695f6b2f5cec6932879ee",
|
||||
"apps/ui/tests/e2e/onboarding.spec.js": "b9172a9186e6adae2e2661543e6a1a289be69fff5e17043817d5ef4f33868436",
|
||||
"apps/ui/tests/e2e/operations.spec.js": "ce19bb50c55e6f00eb643f12fead6ad29c8b6902c417daf3b26b57c1e3fa5968",
|
||||
"apps/ui/tests/e2e/login-readiness.spec.js": "f211cddb8d7d56d2da4b7f645ddde4dac96b85af0bda75eaafba72675df890a4"
|
||||
},
|
||||
"artifact": "./evidence/pr-browser-browser-pr-final-full-suite.txt",
|
||||
"raw_log_sha256": "2eccc64295ff76a61b2f1a0ee903970ee6c7a68d0a814d27e1085f9cf92bccf7",
|
||||
"artifact_sha256": "a374e53cb42c0868435a8a481bda0e4eea84fd005243ab4b1d4342e82c103f03"
|
||||
}
|
||||
],
|
||||
"source_equivalence": {
|
||||
"production_reference": "fa320c34cbe1649a7ef45969a5b7b42953066ad1",
|
||||
"statement": "Производственный код UI/Rust, Dockerfile, Cargo и скрипты совпадают с версией, на которой CI №816 успешно выполнил Rust Checks, UI Checks и Community Image Smoke. Изменены только браузерные тесты и документация."
|
||||
},
|
||||
"artifact_normalization": "Пути обезличены, концевые пробелы удалены. Строка названия теста однократного раскрытия ключа получила такую же точечную директиву Community scope, как в исходном тесте. SHA исходных журналов сохранены отдельно.",
|
||||
"limitations": [
|
||||
"Предыдущий полный прогон 55/56 с отказом CSRF сохранён как неуспешный; результат не исправлен задним числом.",
|
||||
"Квалификационные человеческие, эталонные и длительные испытания не выполнялись.",
|
||||
"Окончательный серверный CI отражается в PR #83 отдельно от этих локальных результатов."
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
{
|
||||
"status": "pass",
|
||||
"purpose": "Проверки изолированного переноса исправлений эпика 1 в PR #83",
|
||||
"implementation_revision": "fa320c34cbe1649a7ef45969a5b7b42953066ad1",
|
||||
"base_revision": "82b215dd74a130e071265ab4d10850aaa28f06a1",
|
||||
"runs": [
|
||||
{
|
||||
"revision": "18e27f39949153b10b296ddf618e9d0b3d61b0fe",
|
||||
"branch": "fix/epic-1-retrospective-20261004",
|
||||
"command": "just verify",
|
||||
"exit_code": 0,
|
||||
"started_utc": "2026-10-04T21:07:34.719722+00:00",
|
||||
"finished_utc": "2026-10-04T21:47:14.062025+00:00",
|
||||
"artifact": "./evidence/pr-integration-rust-gate.txt",
|
||||
"raw_log_sha256": "7772a70edd62d79968ce5046e3a522ff79ddc1a4fdb01359e09cd125fd7a3d71",
|
||||
"artifact_sha256": "fec7f47f8f51f5c776262884810363cb16c10a6f8f020bd55ccaeb82dc67d45b"
|
||||
},
|
||||
{
|
||||
"revision": "fa320c34cbe1649a7ef45969a5b7b42953066ad1",
|
||||
"command": "PLAYWRIGHT_SKIP_WEB_SERVER=1 CI= npm run e2e -- tests/e2e/onboarding.spec.js tests/e2e/operation-lifecycle.spec.js tests/e2e/agents.spec.js --workers=1 --retries=0",
|
||||
"exit_code": 0,
|
||||
"clean_at_start": true,
|
||||
"clean_at_end": true,
|
||||
"artifact": "./evidence/pr-integration-real-stack-final-playwright.txt",
|
||||
"raw_log_sha256": "89bc987a55753a49f202fb0140436a401a836a99b78fb2754499b7ba8e627c4a",
|
||||
"artifact_sha256": "42aaee3efaa9fd41f1eaab3b18e8ccf855e4eb868a57be21e0f736d77e16eb15"
|
||||
},
|
||||
{
|
||||
"revision": "fa320c34cbe1649a7ef45969a5b7b42953066ad1",
|
||||
"command": "node docs/epic-1-completion/evidence/agent-probe.cjs",
|
||||
"exit_code": 0,
|
||||
"clean_at_start": true,
|
||||
"clean_at_end": true,
|
||||
"artifact": "./evidence/pr-integration-agent-final-browser-probe.txt",
|
||||
"raw_log_sha256": "55c4b072392bc6b6b1d0ace014877cd936c3aa5fca66e18e8a412892e46e317b",
|
||||
"artifact_sha256": "55c4b072392bc6b6b1d0ace014877cd936c3aa5fca66e18e8a412892e46e317b"
|
||||
}
|
||||
],
|
||||
"results": {
|
||||
"rust_passed": 878,
|
||||
"rust_failed": 0,
|
||||
"rust_ignored": 1,
|
||||
"tooling_passed": 143,
|
||||
"playwright": {
|
||||
"startTime": "2026-10-04T21:53:32.547Z",
|
||||
"duration": 75034.69799999999,
|
||||
"expected": 15,
|
||||
"skipped": 0,
|
||||
"unexpected": 0,
|
||||
"flaky": 0
|
||||
},
|
||||
"agent_probe_assertions_passed": 5
|
||||
},
|
||||
"source_equivalence": {
|
||||
"rust_revision": "18e27f39949153b10b296ddf618e9d0b3d61b0fe",
|
||||
"browser_revision": "fa320c34cbe1649a7ef45969a5b7b42953066ad1",
|
||||
"changed_paths": [
|
||||
"apps/admin-api/Dockerfile",
|
||||
"apps/mcp-server/Dockerfile"
|
||||
],
|
||||
"statement": "Между Rust gate и браузерным прогоном изменены только COPY vendor в Dockerfile. Исходники, тесты, Cargo и скрипты совпадают."
|
||||
},
|
||||
"limitations": [
|
||||
"Исторический index.json сохранён и относится к другой локальной ветке; его результаты не подменяют этот запуск.",
|
||||
"Человеческая приёмка, внешние эталонные измерения и длительные испытания не выполнялись.",
|
||||
"Серверный CI проверяется отдельно в Gitea."
|
||||
],
|
||||
"artifact_normalization": "В опубликованных журналах обезличены пути, удалены концевые пробелы и пустые строки в конце; SHA исходных журналов сохранены отдельно. В строке названия браузерного теста добавлена такая же точечная директива Community scope, как в исходном тесте; она относится к однократному раскрытию API-ключа, а не к отдельному механизму авторизации."
|
||||
}
|
||||
@@ -20,6 +20,11 @@ DEFAULT_EXCLUDED_PREFIXES = {
|
||||
"target/",
|
||||
"apps/ui/node_modules/",
|
||||
"apps/ui/dist/",
|
||||
# Vendored upstream SQLx source. Its Apache-2.0 license text (commercial)
|
||||
# and upstream migration/pool wording (tenant/billing) are not Community
|
||||
# product features. The prefix is intentionally narrow: only this vendored
|
||||
# package is skipped, and path validation still runs before the skip.
|
||||
"vendor/sqlx-core/",
|
||||
}
|
||||
|
||||
ALLOW_DIRECTIVE = re.compile(
|
||||
|
||||
@@ -19,6 +19,12 @@ declare -A FILE_LIMITS=(
|
||||
)
|
||||
|
||||
status=0
|
||||
source_roots=()
|
||||
for source_dir in apps crates; do
|
||||
if [[ -d "$ROOT_DIR/$source_dir" ]]; then
|
||||
source_roots+=("$ROOT_DIR/$source_dir")
|
||||
fi
|
||||
done
|
||||
|
||||
echo "Rust code health: checking file size limits"
|
||||
|
||||
@@ -32,10 +38,11 @@ while IFS= read -r file; do
|
||||
status=1
|
||||
fi
|
||||
done < <(
|
||||
find "$ROOT_DIR" \
|
||||
-path "$ROOT_DIR/target" -prune -o \
|
||||
-path "$ROOT_DIR/apps/ui/node_modules" -prune -o \
|
||||
-name '*.rs' -print | sort
|
||||
for source_root in "${source_roots[@]}"; do
|
||||
find "$source_root" \
|
||||
-type d \( -name target -o -name node_modules \) -prune -o \
|
||||
-type f -name '*.rs' -print
|
||||
done | sort
|
||||
)
|
||||
|
||||
echo "Rust code health: checking large inline test modules"
|
||||
|
||||
@@ -312,6 +312,77 @@ class CommunityScopeCheckTests(unittest.TestCase):
|
||||
self.assertFalse(truncated)
|
||||
self.assertEqual(scanned_bytes, 0)
|
||||
|
||||
def test_skips_vendored_upstream_sqlx_core_prefix(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
vendored = root / "vendor" / "sqlx-core"
|
||||
(vendored / "src" / "pool").mkdir(parents=True)
|
||||
(vendored / "LICENSE-APACHE").write_text(
|
||||
"commercial damages or losses\n", encoding="utf-8"
|
||||
)
|
||||
(vendored / "src" / "pool" / "options.rs").write_text(
|
||||
"usage-based database server billing\n", encoding="utf-8"
|
||||
)
|
||||
(vendored / "src" / "migrate.rs").write_text(
|
||||
"tenant reference\n", encoding="utf-8"
|
||||
)
|
||||
|
||||
result = self.run_checker(
|
||||
root,
|
||||
[
|
||||
"vendor/sqlx-core/LICENSE-APACHE",
|
||||
"vendor/sqlx-core/src/pool/options.rs",
|
||||
"vendor/sqlx-core/src/migrate.rs",
|
||||
],
|
||||
)
|
||||
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("Community scope check passed", result.stdout)
|
||||
|
||||
def test_forbidden_markers_outside_skipped_prefix_are_rejected(self) -> None:
|
||||
cases = {
|
||||
"vendor/other/scope.txt": ("tenant reference\n", "tenant"),
|
||||
"vendor/sqlx-core-extra/scope.txt": ("billing note\n", "billing"),
|
||||
"apps/scope.txt": ("graphql transport\n", "graphql"),
|
||||
"crates/scope.txt": ("commercial plan\n", "commercial"),
|
||||
}
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
for relative_path, (content, marker) in cases.items():
|
||||
path = root / relative_path
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(content, encoding="utf-8")
|
||||
with self.subTest(relative_path=relative_path):
|
||||
result = self.run_checker(root, [relative_path])
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn(
|
||||
f"{relative_path}:1: forbidden marker `{marker}`",
|
||||
result.stderr,
|
||||
)
|
||||
|
||||
def test_skipped_prefix_paths_are_validated_before_skip(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
vendored = root / "vendor" / "sqlx-core"
|
||||
vendored.mkdir(parents=True)
|
||||
target = vendored / "target.txt"
|
||||
target.write_text("clean\n", encoding="utf-8")
|
||||
link = vendored / "link.txt"
|
||||
link.symlink_to(target)
|
||||
|
||||
valid_excluded = self.run_checker(root, ["vendor/sqlx-core/target.txt"])
|
||||
self.assertEqual(valid_excluded.returncode, 0, valid_excluded.stderr)
|
||||
|
||||
for raw_path in [
|
||||
"vendor/sqlx-core/missing.txt",
|
||||
"vendor/sqlx-core/../other/missing.txt",
|
||||
"vendor/sqlx-core/link.txt",
|
||||
]:
|
||||
with self.subTest(raw_path=raw_path):
|
||||
rejected = self.run_checker(root, [raw_path])
|
||||
self.assertNotEqual(rejected.returncode, 0)
|
||||
self.assertIn("invalid explicit file path", rejected.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -41,7 +41,7 @@ class RustCodeHealthCheckTests(unittest.TestCase):
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("checking file size limits", result.stdout)
|
||||
|
||||
def test_fails_for_new_large_rust_file(self) -> None:
|
||||
def test_fails_for_new_untracked_large_rust_file_in_source_scope(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
self.prepare_root(root)
|
||||
@@ -55,6 +55,46 @@ class RustCodeHealthCheckTests(unittest.TestCase):
|
||||
self.assertNotEqual(result.returncode, 0)
|
||||
self.assertIn("apps/demo/src/large.rs has 21 lines", result.stderr)
|
||||
|
||||
def test_ignores_large_rust_in_nested_bmad_worktree(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
self.prepare_root(root)
|
||||
worktree = (
|
||||
root
|
||||
/ ".bmad-loop"
|
||||
/ "runs"
|
||||
/ "epic-1"
|
||||
/ "worktrees"
|
||||
/ "fixture"
|
||||
)
|
||||
worktree.mkdir(parents=True)
|
||||
(worktree / "large.rs").write_text(
|
||||
"\n".join("// line" for _ in range(21)) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
result = self.run_checker(root)
|
||||
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
def test_ignores_rust_under_nested_target_and_node_modules(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
self.prepare_root(root)
|
||||
generated_dirs = (
|
||||
root / "apps" / "demo" / "target" / "generated",
|
||||
root / "apps" / "demo" / "src" / "node_modules" / "fixture",
|
||||
root / "crates" / "demo" / "node_modules" / "fixture",
|
||||
)
|
||||
large_source = "\n".join("// generated" for _ in range(21)) + "\n"
|
||||
for directory in generated_dirs:
|
||||
directory.mkdir(parents=True)
|
||||
(directory / "large.rs").write_text(large_source, encoding="utf-8")
|
||||
|
||||
result = self.run_checker(root)
|
||||
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
def test_fails_for_large_inline_test_module(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"git": {
|
||||
"sha1": "003b698e99e024f3621b8043a2426fde5b741171"
|
||||
},
|
||||
"path_in_vcs": "sqlx-core"
|
||||
}
|
||||
+2675
File diff suppressed because it is too large.
Load diff
Vendored
+331
@@ -0,0 +1,331 @@
|
||||
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
|
||||
#
|
||||
# When uploading crates to the registry Cargo will automatically
|
||||
# "normalize" Cargo.toml files for maximal compatibility
|
||||
# with all versions of Cargo and also rewrite `path` dependencies
|
||||
# to registry (e.g., crates.io) dependencies.
|
||||
#
|
||||
# If you are reading this file be aware that the original Cargo.toml
|
||||
# will likely look very different (and much more reasonable).
|
||||
# See Cargo.toml.orig for the original contents.
|
||||
|
||||
[package]
|
||||
edition = "2021"
|
||||
rust-version = "1.94.0"
|
||||
name = "sqlx-core"
|
||||
version = "0.9.0"
|
||||
authors = [
|
||||
"Ryan Leckey <leckey.ryan@gmail.com>",
|
||||
"Austin Bonander <austin.bonander@gmail.com>",
|
||||
"Chloe Ross <orangesnowfox@gmail.com>",
|
||||
"Daniel Akhterov <akhterovd@gmail.com>",
|
||||
]
|
||||
build = false
|
||||
autolib = false
|
||||
autobins = false
|
||||
autoexamples = false
|
||||
autotests = false
|
||||
autobenches = false
|
||||
description = "Core of SQLx, the rust SQL toolkit. Not intended to be used directly."
|
||||
readme = false
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/launchbadge/sqlx"
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = ["offline"]
|
||||
|
||||
[features]
|
||||
_rt-async-global-executor = [
|
||||
"async-global-executor",
|
||||
"_rt-async-io",
|
||||
"_rt-async-task",
|
||||
]
|
||||
_rt-async-io = [
|
||||
"async-io",
|
||||
"async-fs",
|
||||
]
|
||||
_rt-async-std = [
|
||||
"async-std",
|
||||
"_rt-async-io",
|
||||
]
|
||||
_rt-async-task = ["async-task"]
|
||||
_rt-smol = [
|
||||
"smol",
|
||||
"_rt-async-io",
|
||||
"_rt-async-task",
|
||||
]
|
||||
_rt-tokio = [
|
||||
"tokio",
|
||||
"tokio-stream",
|
||||
]
|
||||
_tls-native-tls = ["native-tls"]
|
||||
_tls-none = []
|
||||
_tls-rustls = ["rustls"]
|
||||
_tls-rustls-aws-lc-rs = [
|
||||
"_tls-rustls",
|
||||
"rustls/aws-lc-rs",
|
||||
"webpki-roots",
|
||||
]
|
||||
_tls-rustls-ring-native-roots = [
|
||||
"_tls-rustls",
|
||||
"rustls/ring",
|
||||
"rustls-native-certs",
|
||||
]
|
||||
_tls-rustls-ring-webpki = [
|
||||
"_tls-rustls",
|
||||
"rustls/ring",
|
||||
"webpki-roots",
|
||||
]
|
||||
_unstable-doc = ["sqlx-toml"]
|
||||
any = []
|
||||
default = []
|
||||
json = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
migrate = [
|
||||
"sha2",
|
||||
"crc",
|
||||
]
|
||||
offline = [
|
||||
"serde",
|
||||
"either/serde",
|
||||
]
|
||||
sqlx-toml = [
|
||||
"serde",
|
||||
"toml/parse",
|
||||
]
|
||||
|
||||
[lib]
|
||||
name = "sqlx_core"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[dependencies.async-fs]
|
||||
version = "2.1"
|
||||
optional = true
|
||||
|
||||
[dependencies.async-global-executor]
|
||||
version = "3.1"
|
||||
features = ["async-io"]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[dependencies.async-io]
|
||||
version = "2.4.1"
|
||||
optional = true
|
||||
|
||||
[dependencies.async-std]
|
||||
version = "1.13"
|
||||
optional = true
|
||||
|
||||
[dependencies.async-task]
|
||||
version = "4.7.1"
|
||||
optional = true
|
||||
|
||||
[dependencies.base64]
|
||||
version = "0.22.1"
|
||||
features = ["alloc"]
|
||||
default-features = false
|
||||
|
||||
[dependencies.bigdecimal]
|
||||
version = "0.4.0"
|
||||
optional = true
|
||||
|
||||
[dependencies.bit-vec]
|
||||
version = "0.8"
|
||||
optional = true
|
||||
|
||||
[dependencies.bstr]
|
||||
version = "1.0.1"
|
||||
features = ["std"]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[dependencies.bytes]
|
||||
version = "1.2.0"
|
||||
|
||||
[dependencies.cfg-if]
|
||||
version = "1.0.0"
|
||||
|
||||
[dependencies.chrono]
|
||||
version = "0.4.34"
|
||||
features = [
|
||||
"std",
|
||||
"clock",
|
||||
]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[dependencies.crc]
|
||||
version = "3"
|
||||
optional = true
|
||||
|
||||
[dependencies.crossbeam-queue]
|
||||
version = "0.3.2"
|
||||
|
||||
[dependencies.either]
|
||||
version = "1.6.1"
|
||||
|
||||
[dependencies.event-listener]
|
||||
version = "5.2.0"
|
||||
|
||||
[dependencies.futures-core]
|
||||
version = "0.3.32"
|
||||
default-features = false
|
||||
|
||||
[dependencies.futures-intrusive]
|
||||
version = "0.5.0"
|
||||
|
||||
[dependencies.futures-io]
|
||||
version = "0.3.32"
|
||||
|
||||
[dependencies.futures-util]
|
||||
version = "0.3.32"
|
||||
features = [
|
||||
"alloc",
|
||||
"sink",
|
||||
"io",
|
||||
]
|
||||
default-features = false
|
||||
|
||||
[dependencies.hashbrown]
|
||||
version = "0.16.0"
|
||||
|
||||
[dependencies.hashlink]
|
||||
version = "0.11.0"
|
||||
|
||||
[dependencies.indexmap]
|
||||
version = "2.0"
|
||||
|
||||
[dependencies.ipnet]
|
||||
version = "2.3.0"
|
||||
optional = true
|
||||
|
||||
[dependencies.ipnetwork]
|
||||
version = "0.21.1"
|
||||
optional = true
|
||||
|
||||
[dependencies.log]
|
||||
version = "0.4.18"
|
||||
default-features = false
|
||||
|
||||
[dependencies.mac_address]
|
||||
version = "1.1.5"
|
||||
optional = true
|
||||
|
||||
[dependencies.memchr]
|
||||
version = "2.5.0"
|
||||
default-features = false
|
||||
|
||||
[dependencies.native-tls]
|
||||
version = "0.2.10"
|
||||
optional = true
|
||||
|
||||
[dependencies.percent-encoding]
|
||||
version = "2.3.0"
|
||||
|
||||
[dependencies.rust_decimal]
|
||||
version = "1.36.0"
|
||||
features = ["std"]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[dependencies.rustls]
|
||||
version = "0.23.24"
|
||||
features = [
|
||||
"std",
|
||||
"tls12",
|
||||
]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[dependencies.rustls-native-certs]
|
||||
version = "0.8.0"
|
||||
optional = true
|
||||
|
||||
[dependencies.serde]
|
||||
version = "1.0.219"
|
||||
features = [
|
||||
"derive",
|
||||
"rc",
|
||||
]
|
||||
optional = true
|
||||
|
||||
[dependencies.serde_json]
|
||||
version = "1.0.142"
|
||||
features = ["raw_value"]
|
||||
optional = true
|
||||
|
||||
[dependencies.sha2]
|
||||
version = "0.10.0"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[dependencies.smallvec]
|
||||
version = "1.13.1"
|
||||
|
||||
[dependencies.smol]
|
||||
version = "2.0"
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[dependencies.thiserror]
|
||||
version = "2.0.18"
|
||||
features = ["std"]
|
||||
default-features = false
|
||||
|
||||
[dependencies.time]
|
||||
version = "0.3.47"
|
||||
features = [
|
||||
"formatting",
|
||||
"parsing",
|
||||
"macros",
|
||||
]
|
||||
optional = true
|
||||
|
||||
[dependencies.tokio]
|
||||
version = "1.25.0"
|
||||
features = [
|
||||
"time",
|
||||
"net",
|
||||
"sync",
|
||||
"fs",
|
||||
"io-util",
|
||||
"rt",
|
||||
]
|
||||
optional = true
|
||||
default-features = false
|
||||
|
||||
[dependencies.tokio-stream]
|
||||
version = "0.1.8"
|
||||
features = ["fs"]
|
||||
optional = true
|
||||
|
||||
[dependencies.toml]
|
||||
version = "0.8.16"
|
||||
optional = true
|
||||
|
||||
[dependencies.tracing]
|
||||
version = "0.1.37"
|
||||
features = ["log"]
|
||||
|
||||
[dependencies.url]
|
||||
version = "2.2.2"
|
||||
|
||||
[dependencies.uuid]
|
||||
version = "1.12.1"
|
||||
optional = true
|
||||
|
||||
[dependencies.webpki-roots]
|
||||
version = "1"
|
||||
optional = true
|
||||
|
||||
[dev-dependencies.tokio]
|
||||
version = "1.25.0"
|
||||
features = ["rt"]
|
||||
|
||||
[lints.clippy]
|
||||
cast_possible_truncation = "deny"
|
||||
cast_possible_wrap = "deny"
|
||||
cast_sign_loss = "deny"
|
||||
disallowed_methods = "deny"
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
[package]
|
||||
name = "sqlx-core"
|
||||
description = "Core of SQLx, the rust SQL toolkit. Not intended to be used directly."
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
authors.workspace = true
|
||||
repository.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
features = ["offline"]
|
||||
|
||||
[features]
|
||||
default = []
|
||||
migrate = ["sha2", "crc"]
|
||||
|
||||
any = []
|
||||
|
||||
json = ["serde", "serde_json"]
|
||||
|
||||
# for conditional compilation
|
||||
_rt-async-global-executor = ["async-global-executor", "_rt-async-io", "_rt-async-task"]
|
||||
_rt-async-io = ["async-io", "async-fs"] # see note at async-fs declaration
|
||||
_rt-async-std = ["async-std", "_rt-async-io"]
|
||||
_rt-async-task = ["async-task"]
|
||||
_rt-smol = ["smol", "_rt-async-io", "_rt-async-task"]
|
||||
_rt-tokio = ["tokio", "tokio-stream"]
|
||||
|
||||
_tls-native-tls = ["native-tls"]
|
||||
_tls-rustls-aws-lc-rs = ["_tls-rustls", "rustls/aws-lc-rs", "webpki-roots"]
|
||||
_tls-rustls-ring-webpki = ["_tls-rustls", "rustls/ring", "webpki-roots"]
|
||||
_tls-rustls-ring-native-roots = ["_tls-rustls", "rustls/ring", "rustls-native-certs"]
|
||||
_tls-rustls = ["rustls"]
|
||||
_tls-none = []
|
||||
|
||||
# support offline/decoupled building (enables serialization of `Describe`)
|
||||
offline = ["serde", "either/serde"]
|
||||
|
||||
# Enable parsing of `sqlx.toml`.
|
||||
# For simplicity, the `config` module is always enabled,
|
||||
# but disabling this disables the `serde` derives and the `toml` crate,
|
||||
# which is a good bit less code to compile if the feature isn't being used.
|
||||
sqlx-toml = ["serde", "toml/parse"]
|
||||
|
||||
_unstable-doc = ["sqlx-toml"]
|
||||
|
||||
[dependencies]
|
||||
# Runtimes
|
||||
async-global-executor = { workspace = true, optional = true }
|
||||
async-std = { workspace = true, optional = true }
|
||||
smol = { workspace = true, optional = true }
|
||||
tokio = { workspace = true, optional = true }
|
||||
|
||||
# TLS
|
||||
native-tls = { version = "0.2.10", optional = true }
|
||||
|
||||
rustls = { version = "0.23.24", default-features = false, features = ["std", "tls12"], optional = true }
|
||||
webpki-roots = { version = "1", optional = true }
|
||||
rustls-native-certs = { version = "0.8.0", optional = true }
|
||||
|
||||
# Type Integrations
|
||||
bit-vec = { workspace = true, optional = true }
|
||||
bigdecimal = { workspace = true, optional = true }
|
||||
chrono = { workspace = true, optional = true }
|
||||
rust_decimal = { workspace = true, optional = true }
|
||||
time = { workspace = true, optional = true }
|
||||
ipnet = { workspace = true, optional = true }
|
||||
ipnetwork = { workspace = true, optional = true }
|
||||
mac_address = { workspace = true, optional = true }
|
||||
uuid = { workspace = true, optional = true }
|
||||
|
||||
# work around bug in async-fs 2.0.0, which references futures-lite dependency wrongly, see https://github.com/launchbadge/sqlx/pull/3791#issuecomment-3043363281
|
||||
async-fs = { version = "2.1", optional = true }
|
||||
async-io = { version = "2.4.1", optional = true }
|
||||
async-task = { version = "4.7.1", optional = true }
|
||||
|
||||
base64.workspace = true
|
||||
bytes = "1.2.0"
|
||||
cfg-if = { workspace = true }
|
||||
crc = { version = "3", optional = true }
|
||||
crossbeam-queue = "0.3.2"
|
||||
either = "1.6.1"
|
||||
futures-core = { version = "0.3.32", default-features = false }
|
||||
futures-io = "0.3.32"
|
||||
futures-intrusive = "0.5.0"
|
||||
futures-util = { version = "0.3.32", default-features = false, features = ["alloc", "sink", "io"] }
|
||||
log = { version = "0.4.18", default-features = false }
|
||||
memchr = { version = "2.5.0", default-features = false }
|
||||
percent-encoding = "2.3.0"
|
||||
serde = { version = "1.0.219", features = ["derive", "rc"], optional = true }
|
||||
serde_json = { version = "1.0.142", features = ["raw_value"], optional = true }
|
||||
toml = { version = "0.8.16", optional = true }
|
||||
sha2 = { version = "0.10.0", default-features = false, optional = true }
|
||||
#sqlformat = "0.2.0"
|
||||
tokio-stream = { version = "0.1.8", features = ["fs"], optional = true }
|
||||
tracing = { version = "0.1.37", features = ["log"] }
|
||||
smallvec = "1.13.1"
|
||||
url = { version = "2.2.2" }
|
||||
bstr = { version = "1.0.1", default-features = false, features = ["std"], optional = true }
|
||||
hashlink = "0.11.0"
|
||||
indexmap = "2.0"
|
||||
event-listener = "5.2.0"
|
||||
hashbrown = "0.16.0"
|
||||
|
||||
thiserror.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { version = "1.25.0", features = ["rt"] }
|
||||
|
||||
[dev-dependencies.sqlx]
|
||||
# FIXME: https://github.com/rust-lang/cargo/issues/15622
|
||||
# workspace = true
|
||||
path = ".."
|
||||
default-features = false
|
||||
features = ["postgres", "sqlite", "mysql", "migrate", "macros", "time", "uuid"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright (C) SQLx Contributors
|
||||
Portions of this work Copyright (C) LaunchBadge, LLC
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
Copyright (C) SQLx Contributors
|
||||
Portions of this work Copyright (C) LaunchBadge, LLC
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
use crate::database::Database;
|
||||
use crate::error::Error;
|
||||
use crate::pool::{MaybePoolConnection, Pool, PoolConnection};
|
||||
|
||||
use crate::transaction::Transaction;
|
||||
use futures_core::future::BoxFuture;
|
||||
use std::ops::{Deref, DerefMut};
|
||||
|
||||
/// Acquire connections or transactions from a database in a generic way.
|
||||
///
|
||||
/// If you want to accept generic database connections that implement
|
||||
/// [`Acquire`] which then allows you to [`acquire`][`Acquire::acquire`] a
|
||||
/// connection or [`begin`][`Acquire::begin`] a transaction, then you can do it
|
||||
/// like that:
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// # use sqlx::{Acquire, postgres::Postgres, error::BoxDynError};
|
||||
/// async fn run_query<'a, A>(conn: A) -> Result<(), BoxDynError>
|
||||
/// where
|
||||
/// A: Acquire<'a, Database = Postgres>,
|
||||
/// {
|
||||
/// let mut conn = conn.acquire().await?;
|
||||
///
|
||||
/// sqlx::query!("SELECT 1 as v").fetch_one(&mut *conn).await?;
|
||||
/// sqlx::query!("SELECT 2 as v").fetch_one(&mut *conn).await?;
|
||||
///
|
||||
/// Ok(())
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// If you run into a lifetime error about "implementation of `sqlx::Acquire` is
|
||||
/// not general enough", the [workaround] looks like this:
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// # use std::future::Future;
|
||||
/// # use sqlx::{Acquire, postgres::Postgres, error::BoxDynError};
|
||||
/// fn run_query<'a, 'c, A>(conn: A) -> impl Future<Output = Result<(), BoxDynError>> + Send + 'a
|
||||
/// where
|
||||
/// A: Acquire<'c, Database = Postgres> + Send + 'a,
|
||||
/// {
|
||||
/// async move {
|
||||
/// let mut conn = conn.acquire().await?;
|
||||
///
|
||||
/// sqlx::query!("SELECT 1 as v").fetch_one(&mut *conn).await?;
|
||||
/// sqlx::query!("SELECT 2 as v").fetch_one(&mut *conn).await?;
|
||||
///
|
||||
/// Ok(())
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// However, if you really just want to accept both, a transaction or a
|
||||
/// connection as an argument to a function, then it's easier to just accept a
|
||||
/// mutable reference to a database connection like so:
|
||||
///
|
||||
/// ```rust,ignore
|
||||
/// # use sqlx::{postgres::PgConnection, error::BoxDynError};
|
||||
/// async fn run_query(conn: &mut PgConnection) -> Result<(), BoxDynError> {
|
||||
/// sqlx::query!("SELECT 1 as v").fetch_one(&mut *conn).await?;
|
||||
/// sqlx::query!("SELECT 2 as v").fetch_one(&mut *conn).await?;
|
||||
///
|
||||
/// Ok(())
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The downside of this approach is that you have to `acquire` a connection
|
||||
/// from a pool first and can't directly pass the pool as argument.
|
||||
///
|
||||
/// [workaround]: https://github.com/launchbadge/sqlx/issues/1015#issuecomment-767787777
|
||||
pub trait Acquire<'c> {
|
||||
type Database: Database;
|
||||
|
||||
type Connection: Deref<Target = <Self::Database as Database>::Connection> + DerefMut + Send;
|
||||
|
||||
fn acquire(self) -> BoxFuture<'c, Result<Self::Connection, Error>>;
|
||||
|
||||
fn begin(self) -> BoxFuture<'c, Result<Transaction<'c, Self::Database>, Error>>;
|
||||
}
|
||||
|
||||
impl<'a, DB: Database> Acquire<'a> for &'_ Pool<DB> {
|
||||
type Database = DB;
|
||||
|
||||
type Connection = PoolConnection<DB>;
|
||||
|
||||
fn acquire(self) -> BoxFuture<'static, Result<Self::Connection, Error>> {
|
||||
Box::pin(self.acquire())
|
||||
}
|
||||
|
||||
fn begin(self) -> BoxFuture<'static, Result<Transaction<'a, DB>, Error>> {
|
||||
let conn = self.acquire();
|
||||
|
||||
Box::pin(async move {
|
||||
Transaction::begin(MaybePoolConnection::PoolConnection(conn.await?), None).await
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! impl_acquire {
|
||||
($DB:ident, $C:ident) => {
|
||||
impl<'c> $crate::acquire::Acquire<'c> for &'c mut $C {
|
||||
type Database = $DB;
|
||||
|
||||
type Connection = &'c mut <$DB as $crate::database::Database>::Connection;
|
||||
|
||||
#[inline]
|
||||
fn acquire(
|
||||
self,
|
||||
) -> futures_core::future::BoxFuture<'c, Result<Self::Connection, $crate::error::Error>>
|
||||
{
|
||||
Box::pin(std::future::ready(Ok(self)))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn begin(
|
||||
self,
|
||||
) -> futures_core::future::BoxFuture<
|
||||
'c,
|
||||
Result<$crate::transaction::Transaction<'c, $DB>, $crate::error::Error>,
|
||||
> {
|
||||
$crate::transaction::Transaction::begin(self, None)
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
use crate::any::value::AnyValueKind;
|
||||
use crate::any::{Any, AnyTypeInfoKind};
|
||||
use crate::arguments::Arguments;
|
||||
use crate::encode::{Encode, IsNull};
|
||||
use crate::error::BoxDynError;
|
||||
use crate::types::Type;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct AnyArguments {
|
||||
#[doc(hidden)]
|
||||
pub values: AnyArgumentBuffer,
|
||||
}
|
||||
|
||||
impl Arguments for AnyArguments {
|
||||
type Database = Any;
|
||||
|
||||
fn reserve(&mut self, additional: usize, _size: usize) {
|
||||
self.values.0.reserve(additional);
|
||||
}
|
||||
|
||||
fn add<'t, T>(&mut self, value: T) -> Result<(), BoxDynError>
|
||||
where
|
||||
T: Encode<'t, Self::Database> + Type<Self::Database>,
|
||||
{
|
||||
let _: IsNull = value.encode(&mut self.values)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn len(&self) -> usize {
|
||||
self.values.0.len()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct AnyArgumentBuffer(#[doc(hidden)] pub Vec<AnyValueKind>);
|
||||
|
||||
impl AnyArguments {
|
||||
#[doc(hidden)]
|
||||
pub fn convert_into<'a, A: Arguments>(self) -> Result<A, BoxDynError>
|
||||
where
|
||||
Option<i32>: Type<A::Database> + Encode<'a, A::Database>,
|
||||
Option<bool>: Type<A::Database> + Encode<'a, A::Database>,
|
||||
Option<i16>: Type<A::Database> + Encode<'a, A::Database>,
|
||||
Option<i32>: Type<A::Database> + Encode<'a, A::Database>,
|
||||
Option<i64>: Type<A::Database> + Encode<'a, A::Database>,
|
||||
Option<f32>: Type<A::Database> + Encode<'a, A::Database>,
|
||||
Option<f64>: Type<A::Database> + Encode<'a, A::Database>,
|
||||
Option<String>: Type<A::Database> + Encode<'a, A::Database>,
|
||||
Option<Vec<u8>>: Type<A::Database> + Encode<'a, A::Database>,
|
||||
bool: Type<A::Database> + Encode<'a, A::Database>,
|
||||
i16: Type<A::Database> + Encode<'a, A::Database>,
|
||||
i32: Type<A::Database> + Encode<'a, A::Database>,
|
||||
i64: Type<A::Database> + Encode<'a, A::Database>,
|
||||
f32: Type<A::Database> + Encode<'a, A::Database>,
|
||||
f64: Type<A::Database> + Encode<'a, A::Database>,
|
||||
Arc<String>: Type<A::Database> + Encode<'a, A::Database>,
|
||||
Arc<str>: Type<A::Database> + Encode<'a, A::Database>,
|
||||
Arc<Vec<u8>>: Type<A::Database> + Encode<'a, A::Database>,
|
||||
{
|
||||
let mut out = A::default();
|
||||
|
||||
for arg in self.values.0 {
|
||||
match arg {
|
||||
AnyValueKind::Null(AnyTypeInfoKind::Null) => out.add(Option::<i32>::None),
|
||||
AnyValueKind::Null(AnyTypeInfoKind::Bool) => out.add(Option::<bool>::None),
|
||||
AnyValueKind::Null(AnyTypeInfoKind::SmallInt) => out.add(Option::<i16>::None),
|
||||
AnyValueKind::Null(AnyTypeInfoKind::Integer) => out.add(Option::<i32>::None),
|
||||
AnyValueKind::Null(AnyTypeInfoKind::BigInt) => out.add(Option::<i64>::None),
|
||||
AnyValueKind::Null(AnyTypeInfoKind::Real) => out.add(Option::<f64>::None),
|
||||
AnyValueKind::Null(AnyTypeInfoKind::Double) => out.add(Option::<f32>::None),
|
||||
AnyValueKind::Null(AnyTypeInfoKind::Text) => out.add(Option::<String>::None),
|
||||
AnyValueKind::Null(AnyTypeInfoKind::Blob) => out.add(Option::<Vec<u8>>::None),
|
||||
AnyValueKind::Bool(b) => out.add(b),
|
||||
AnyValueKind::SmallInt(i) => out.add(i),
|
||||
AnyValueKind::Integer(i) => out.add(i),
|
||||
AnyValueKind::BigInt(i) => out.add(i),
|
||||
AnyValueKind::Real(r) => out.add(r),
|
||||
AnyValueKind::Double(d) => out.add(d),
|
||||
AnyValueKind::Text(t) => out.add(t),
|
||||
AnyValueKind::TextSlice(t) => out.add(t),
|
||||
AnyValueKind::Blob(b) => out.add(b),
|
||||
}?
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
use crate::any::{Any, AnyTypeInfo};
|
||||
use crate::column::Column;
|
||||
use crate::ext::ustr::UStr;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AnyColumn {
|
||||
// NOTE: these fields are semver-exempt. See crate root docs for details.
|
||||
#[doc(hidden)]
|
||||
pub ordinal: usize,
|
||||
|
||||
#[doc(hidden)]
|
||||
pub name: UStr,
|
||||
|
||||
#[doc(hidden)]
|
||||
pub type_info: AnyTypeInfo,
|
||||
}
|
||||
impl Column for AnyColumn {
|
||||
type Database = Any;
|
||||
|
||||
fn ordinal(&self) -> usize {
|
||||
self.ordinal
|
||||
}
|
||||
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
|
||||
fn type_info(&self) -> &AnyTypeInfo {
|
||||
&self.type_info
|
||||
}
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
use crate::any::{AnyArguments, AnyQueryResult, AnyRow, AnyStatement, AnyTypeInfo};
|
||||
use crate::sql_str::SqlStr;
|
||||
use either::Either;
|
||||
use futures_core::future::BoxFuture;
|
||||
use futures_core::stream::BoxStream;
|
||||
use std::fmt::Debug;
|
||||
|
||||
pub trait AnyConnectionBackend: std::any::Any + Debug + Send + 'static {
|
||||
/// The backend name.
|
||||
fn name(&self) -> &str;
|
||||
|
||||
/// Explicitly close this database connection.
|
||||
///
|
||||
/// This method is **not required** for safe and consistent operation. However, it is
|
||||
/// recommended to call it instead of letting a connection `drop` as the database backend
|
||||
/// will be faster at cleaning up resources.
|
||||
fn close(self: Box<Self>) -> BoxFuture<'static, crate::Result<()>>;
|
||||
|
||||
/// Immediately close the connection without sending a graceful shutdown.
|
||||
///
|
||||
/// This should still at least send a TCP `FIN` frame to let the server know we're dying.
|
||||
#[doc(hidden)]
|
||||
fn close_hard(self: Box<Self>) -> BoxFuture<'static, crate::Result<()>>;
|
||||
|
||||
/// Checks if a connection to the database is still valid.
|
||||
fn ping(&mut self) -> BoxFuture<'_, crate::Result<()>>;
|
||||
|
||||
/// Begin a new transaction or establish a savepoint within the active transaction.
|
||||
///
|
||||
/// If this is a new transaction, `statement` may be used instead of the
|
||||
/// default "BEGIN" statement.
|
||||
///
|
||||
/// If we are already inside a transaction and `statement.is_some()`, then
|
||||
/// `Error::InvalidSavePoint` is returned without running any statements.
|
||||
fn begin(&mut self, statement: Option<SqlStr>) -> BoxFuture<'_, crate::Result<()>>;
|
||||
|
||||
fn commit(&mut self) -> BoxFuture<'_, crate::Result<()>>;
|
||||
|
||||
fn rollback(&mut self) -> BoxFuture<'_, crate::Result<()>>;
|
||||
|
||||
fn start_rollback(&mut self);
|
||||
|
||||
/// Returns the current transaction depth.
|
||||
///
|
||||
/// Transaction depth indicates the level of nested transactions:
|
||||
/// - Level 0: No active transaction.
|
||||
/// - Level 1: A transaction is active.
|
||||
/// - Level 2 or higher: A transaction is active and one or more SAVEPOINTs have been created within it.
|
||||
fn get_transaction_depth(&self) -> usize {
|
||||
unimplemented!("get_transaction_depth() is not implemented for this backend. This is a provided method to avoid a breaking change, but it will become a required method in version 0.9 and later.");
|
||||
}
|
||||
|
||||
/// Checks if the connection is currently in a transaction.
|
||||
///
|
||||
/// This method returns `true` if the current transaction depth is greater than 0,
|
||||
/// indicating that a transaction is active. It returns `false` if the transaction depth is 0,
|
||||
/// meaning no transaction is active.
|
||||
#[inline]
|
||||
fn is_in_transaction(&self) -> bool {
|
||||
self.get_transaction_depth() != 0
|
||||
}
|
||||
|
||||
/// The number of statements currently cached in the connection.
|
||||
fn cached_statements_size(&self) -> usize {
|
||||
0
|
||||
}
|
||||
|
||||
/// Removes all statements from the cache, closing them on the server if
|
||||
/// needed.
|
||||
fn clear_cached_statements(&mut self) -> BoxFuture<'_, crate::Result<()>> {
|
||||
Box::pin(async move { Ok(()) })
|
||||
}
|
||||
|
||||
/// Forward to [`Connection::shrink_buffers()`].
|
||||
///
|
||||
/// [`Connection::shrink_buffers()`]: method@crate::connection::Connection::shrink_buffers
|
||||
fn shrink_buffers(&mut self);
|
||||
|
||||
#[doc(hidden)]
|
||||
fn flush(&mut self) -> BoxFuture<'_, crate::Result<()>>;
|
||||
|
||||
#[doc(hidden)]
|
||||
fn should_flush(&self) -> bool;
|
||||
|
||||
#[cfg(feature = "migrate")]
|
||||
fn as_migrate(&mut self) -> crate::Result<&mut (dyn crate::migrate::Migrate + Send + 'static)> {
|
||||
Err(crate::Error::Configuration(
|
||||
format!(
|
||||
"{} driver does not support migrations or `migrate` feature was not enabled",
|
||||
self.name()
|
||||
)
|
||||
.into(),
|
||||
))
|
||||
}
|
||||
|
||||
fn fetch_many(
|
||||
&mut self,
|
||||
query: SqlStr,
|
||||
persistent: bool,
|
||||
arguments: Option<AnyArguments>,
|
||||
) -> BoxStream<'_, crate::Result<Either<AnyQueryResult, AnyRow>>>;
|
||||
|
||||
fn fetch_optional(
|
||||
&mut self,
|
||||
query: SqlStr,
|
||||
persistent: bool,
|
||||
arguments: Option<AnyArguments>,
|
||||
) -> BoxFuture<'_, crate::Result<Option<AnyRow>>>;
|
||||
|
||||
fn prepare_with<'c, 'q: 'c>(
|
||||
&'c mut self,
|
||||
sql: SqlStr,
|
||||
parameters: &[AnyTypeInfo],
|
||||
) -> BoxFuture<'c, crate::Result<AnyStatement>>;
|
||||
|
||||
#[cfg(feature = "offline")]
|
||||
fn describe(
|
||||
&mut self,
|
||||
sql: SqlStr,
|
||||
) -> BoxFuture<'_, crate::Result<crate::describe::Describe<crate::any::Any>>>;
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
use crate::any::{Any, AnyConnection, AnyQueryResult, AnyRow, AnyStatement, AnyTypeInfo};
|
||||
use crate::error::Error;
|
||||
use crate::executor::{Execute, Executor};
|
||||
use crate::sql_str::SqlStr;
|
||||
use either::Either;
|
||||
use futures_core::future::BoxFuture;
|
||||
use futures_core::stream::BoxStream;
|
||||
use futures_util::{stream, FutureExt, StreamExt};
|
||||
use std::future;
|
||||
|
||||
impl<'c> Executor<'c> for &'c mut AnyConnection {
|
||||
type Database = Any;
|
||||
|
||||
fn fetch_many<'e, 'q: 'e, E>(
|
||||
self,
|
||||
mut query: E,
|
||||
) -> BoxStream<'e, Result<Either<AnyQueryResult, AnyRow>, Error>>
|
||||
where
|
||||
'c: 'e,
|
||||
E: 'q + Execute<'q, Any>,
|
||||
{
|
||||
let arguments = match query.take_arguments().map_err(Error::Encode) {
|
||||
Ok(arguments) => arguments,
|
||||
Err(error) => return stream::once(future::ready(Err(error))).boxed(),
|
||||
};
|
||||
let persistent = query.persistent();
|
||||
self.backend.fetch_many(query.sql(), persistent, arguments)
|
||||
}
|
||||
|
||||
fn fetch_optional<'e, 'q: 'e, E>(
|
||||
self,
|
||||
mut query: E,
|
||||
) -> BoxFuture<'e, Result<Option<AnyRow>, Error>>
|
||||
where
|
||||
'c: 'e,
|
||||
E: 'q + Execute<'q, Self::Database>,
|
||||
{
|
||||
let arguments = match query.take_arguments().map_err(Error::Encode) {
|
||||
Ok(arguments) => arguments,
|
||||
Err(error) => return future::ready(Err(error)).boxed(),
|
||||
};
|
||||
let persistent = query.persistent();
|
||||
self.backend
|
||||
.fetch_optional(query.sql(), persistent, arguments)
|
||||
}
|
||||
|
||||
fn prepare_with<'e>(
|
||||
self,
|
||||
sql: SqlStr,
|
||||
parameters: &[AnyTypeInfo],
|
||||
) -> BoxFuture<'e, Result<AnyStatement, Error>>
|
||||
where
|
||||
'c: 'e,
|
||||
{
|
||||
self.backend.prepare_with(sql, parameters)
|
||||
}
|
||||
|
||||
#[cfg(feature = "offline")]
|
||||
fn describe<'e>(
|
||||
self,
|
||||
sql: SqlStr,
|
||||
) -> BoxFuture<'e, Result<crate::describe::Describe<Self::Database>, Error>>
|
||||
where
|
||||
'c: 'e,
|
||||
{
|
||||
self.backend.describe(sql)
|
||||
}
|
||||
}
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
use futures_core::future::BoxFuture;
|
||||
use std::future::Future;
|
||||
|
||||
use crate::any::{Any, AnyConnectOptions};
|
||||
use crate::connection::{ConnectOptions, Connection};
|
||||
use crate::error::Error;
|
||||
|
||||
use crate::config;
|
||||
use crate::database::Database;
|
||||
use crate::sql_str::SqlSafeStr;
|
||||
use crate::transaction::Transaction;
|
||||
pub use backend::AnyConnectionBackend;
|
||||
|
||||
mod backend;
|
||||
mod executor;
|
||||
|
||||
/// A connection to _any_ SQLx database.
|
||||
///
|
||||
/// The database driver used is determined by the scheme
|
||||
/// of the connection url.
|
||||
///
|
||||
/// ```text
|
||||
/// postgres://postgres@localhost/test
|
||||
/// sqlite://a.sqlite
|
||||
/// ```
|
||||
#[derive(Debug)]
|
||||
pub struct AnyConnection {
|
||||
pub(crate) backend: Box<dyn AnyConnectionBackend>,
|
||||
}
|
||||
|
||||
impl AnyConnection {
|
||||
/// Returns the name of the database backend in use (e.g. PostgreSQL, MySQL, SQLite, etc.)
|
||||
pub fn backend_name(&self) -> &str {
|
||||
self.backend.name()
|
||||
}
|
||||
|
||||
pub(crate) fn connect(options: &AnyConnectOptions) -> BoxFuture<'_, crate::Result<Self>> {
|
||||
Box::pin(async {
|
||||
let driver = crate::any::driver::from_url(&options.database_url)?;
|
||||
(*driver.connect)(options, None).await
|
||||
})
|
||||
}
|
||||
|
||||
/// UNSTABLE: for use with `sqlx-cli`
|
||||
///
|
||||
/// Connect to the database, and instruct the nested driver to
|
||||
/// read options from the sqlx.toml file as appropriate.
|
||||
#[doc(hidden)]
|
||||
pub async fn connect_with_driver_config(
|
||||
url: &str,
|
||||
driver_config: &config::drivers::Config,
|
||||
) -> Result<Self, Error>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
let options: AnyConnectOptions = url.parse()?;
|
||||
|
||||
let driver = crate::any::driver::from_url(&options.database_url)?;
|
||||
(*driver.connect)(&options, Some(driver_config)).await
|
||||
}
|
||||
|
||||
pub(crate) fn connect_with_db<'a, DB: Database>(
|
||||
options: &'a AnyConnectOptions,
|
||||
driver_config: Option<&'a config::drivers::Config>,
|
||||
) -> BoxFuture<'a, crate::Result<Self>>
|
||||
where
|
||||
DB::Connection: AnyConnectionBackend,
|
||||
<DB::Connection as Connection>::Options:
|
||||
for<'b> TryFrom<&'b AnyConnectOptions, Error = Error>,
|
||||
{
|
||||
let res = TryFrom::try_from(options);
|
||||
|
||||
Box::pin(async move {
|
||||
let mut options: <DB::Connection as Connection>::Options = res?;
|
||||
|
||||
if let Some(config) = driver_config {
|
||||
options = options.__unstable_apply_driver_config(config)?;
|
||||
}
|
||||
|
||||
Ok(AnyConnection {
|
||||
backend: Box::new(options.connect().await?),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(feature = "migrate")]
|
||||
pub(crate) fn get_migrate(
|
||||
&mut self,
|
||||
) -> crate::Result<&mut (dyn crate::migrate::Migrate + Send + 'static)> {
|
||||
self.backend.as_migrate()
|
||||
}
|
||||
}
|
||||
|
||||
impl Connection for AnyConnection {
|
||||
type Database = Any;
|
||||
|
||||
type Options = AnyConnectOptions;
|
||||
|
||||
fn close(self) -> impl Future<Output = Result<(), Error>> + Send + 'static {
|
||||
self.backend.close()
|
||||
}
|
||||
|
||||
fn close_hard(self) -> impl Future<Output = Result<(), Error>> + Send + 'static {
|
||||
self.backend.close()
|
||||
}
|
||||
|
||||
fn ping(&mut self) -> impl Future<Output = Result<(), Error>> + Send + '_ {
|
||||
self.backend.ping()
|
||||
}
|
||||
|
||||
fn begin(
|
||||
&mut self,
|
||||
) -> impl Future<Output = Result<Transaction<'_, Self::Database>, Error>> + Send + '_
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
Transaction::begin(self, None)
|
||||
}
|
||||
|
||||
fn begin_with(
|
||||
&mut self,
|
||||
statement: impl SqlSafeStr,
|
||||
) -> impl Future<Output = Result<Transaction<'_, Self::Database>, Error>> + Send + '_
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
Transaction::begin(self, Some(statement.into_sql_str()))
|
||||
}
|
||||
|
||||
fn cached_statements_size(&self) -> usize {
|
||||
self.backend.cached_statements_size()
|
||||
}
|
||||
|
||||
fn clear_cached_statements(&mut self) -> impl Future<Output = crate::Result<()>> + Send + '_ {
|
||||
self.backend.clear_cached_statements()
|
||||
}
|
||||
|
||||
fn shrink_buffers(&mut self) {
|
||||
self.backend.shrink_buffers()
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
fn flush(&mut self) -> impl Future<Output = Result<(), Error>> + Send + '_ {
|
||||
self.backend.flush()
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
fn should_flush(&self) -> bool {
|
||||
self.backend.should_flush()
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
use crate::any::{
|
||||
AnyArgumentBuffer, AnyArguments, AnyColumn, AnyConnection, AnyQueryResult, AnyRow,
|
||||
AnyStatement, AnyTransactionManager, AnyTypeInfo, AnyValue, AnyValueRef,
|
||||
};
|
||||
use crate::database::{Database, HasStatementCache};
|
||||
|
||||
/// Opaque database driver. Capable of being used in place of any SQLx database driver. The actual
|
||||
/// driver used will be selected at runtime, from the connection url.
|
||||
#[derive(Debug)]
|
||||
pub struct Any;
|
||||
|
||||
impl Database for Any {
|
||||
type Connection = AnyConnection;
|
||||
|
||||
type TransactionManager = AnyTransactionManager;
|
||||
|
||||
type Row = AnyRow;
|
||||
|
||||
type QueryResult = AnyQueryResult;
|
||||
|
||||
type Column = AnyColumn;
|
||||
|
||||
type TypeInfo = AnyTypeInfo;
|
||||
|
||||
type Value = AnyValue;
|
||||
type ValueRef<'r> = AnyValueRef<'r>;
|
||||
|
||||
type Arguments = AnyArguments;
|
||||
type ArgumentBuffer = AnyArgumentBuffer;
|
||||
|
||||
type Statement = AnyStatement;
|
||||
|
||||
const NAME: &'static str = "Any";
|
||||
|
||||
const URL_SCHEMES: &'static [&'static str] = &[];
|
||||
}
|
||||
|
||||
// This _may_ be true, depending on the selected database
|
||||
impl HasStatementCache for Any {}
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
use crate::any::connection::AnyConnectionBackend;
|
||||
use crate::any::{AnyConnectOptions, AnyConnection};
|
||||
use crate::common::DebugFn;
|
||||
use crate::connection::Connection;
|
||||
use crate::database::Database;
|
||||
use crate::{config, Error};
|
||||
use futures_core::future::BoxFuture;
|
||||
use std::fmt::{Debug, Formatter};
|
||||
use std::sync::OnceLock;
|
||||
use url::Url;
|
||||
|
||||
static DRIVERS: OnceLock<&'static [AnyDriver]> = OnceLock::new();
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! declare_driver_with_optional_migrate {
|
||||
($name:ident = $db:path) => {
|
||||
#[cfg(feature = "migrate")]
|
||||
pub const $name: $crate::any::driver::AnyDriver =
|
||||
$crate::any::driver::AnyDriver::with_migrate::<$db>();
|
||||
|
||||
#[cfg(not(feature = "migrate"))]
|
||||
pub const $name: $crate::any::driver::AnyDriver =
|
||||
$crate::any::driver::AnyDriver::without_migrate::<$db>();
|
||||
};
|
||||
}
|
||||
|
||||
#[non_exhaustive]
|
||||
pub struct AnyDriver {
|
||||
pub(crate) name: &'static str,
|
||||
pub(crate) url_schemes: &'static [&'static str],
|
||||
pub(crate) connect: DebugFn<
|
||||
for<'a> fn(
|
||||
&'a AnyConnectOptions,
|
||||
Option<&'a config::drivers::Config>,
|
||||
) -> BoxFuture<'a, crate::Result<AnyConnection>>,
|
||||
>,
|
||||
pub(crate) migrate_database: Option<AnyMigrateDatabase>,
|
||||
}
|
||||
|
||||
impl AnyDriver {
|
||||
pub const fn without_migrate<DB: Database>() -> Self
|
||||
where
|
||||
DB::Connection: AnyConnectionBackend,
|
||||
<DB::Connection as Connection>::Options:
|
||||
for<'a> TryFrom<&'a AnyConnectOptions, Error = Error>,
|
||||
{
|
||||
Self {
|
||||
name: DB::NAME,
|
||||
url_schemes: DB::URL_SCHEMES,
|
||||
connect: DebugFn(AnyConnection::connect_with_db::<DB>),
|
||||
migrate_database: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "migrate"))]
|
||||
pub const fn with_migrate<DB: Database>() -> Self
|
||||
where
|
||||
DB::Connection: AnyConnectionBackend,
|
||||
<DB::Connection as Connection>::Options:
|
||||
for<'a> TryFrom<&'a AnyConnectOptions, Error = Error>,
|
||||
{
|
||||
Self::without_migrate::<DB>()
|
||||
}
|
||||
|
||||
#[cfg(feature = "migrate")]
|
||||
pub const fn with_migrate<DB: Database + crate::migrate::MigrateDatabase>() -> Self
|
||||
where
|
||||
DB::Connection: AnyConnectionBackend,
|
||||
<DB::Connection as Connection>::Options:
|
||||
for<'a> TryFrom<&'a AnyConnectOptions, Error = Error>,
|
||||
{
|
||||
Self {
|
||||
migrate_database: Some(AnyMigrateDatabase {
|
||||
create_database: DebugFn(|url| Box::pin(DB::create_database(url))),
|
||||
database_exists: DebugFn(|url| Box::pin(DB::database_exists(url))),
|
||||
drop_database: DebugFn(|url| Box::pin(DB::drop_database(url))),
|
||||
force_drop_database: DebugFn(|url| Box::pin(DB::force_drop_database(url))),
|
||||
}),
|
||||
..Self::without_migrate::<DB>()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_migrate_database(&self) -> crate::Result<&AnyMigrateDatabase> {
|
||||
self.migrate_database.as_ref()
|
||||
.ok_or_else(|| Error::Configuration(format!("{} driver does not support migrations or the `migrate` feature was not enabled for it", self.name).into()))
|
||||
}
|
||||
}
|
||||
|
||||
impl Debug for AnyDriver {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("AnyDriver")
|
||||
.field("name", &self.name)
|
||||
.field("url_schemes", &self.url_schemes)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct AnyMigrateDatabase {
|
||||
create_database: DebugFn<fn(&str) -> BoxFuture<'_, crate::Result<()>>>,
|
||||
database_exists: DebugFn<fn(&str) -> BoxFuture<'_, crate::Result<bool>>>,
|
||||
drop_database: DebugFn<fn(&str) -> BoxFuture<'_, crate::Result<()>>>,
|
||||
force_drop_database: DebugFn<fn(&str) -> BoxFuture<'_, crate::Result<()>>>,
|
||||
}
|
||||
|
||||
impl AnyMigrateDatabase {
|
||||
pub fn create_database<'a>(&self, url: &'a str) -> BoxFuture<'a, crate::Result<()>> {
|
||||
(self.create_database)(url)
|
||||
}
|
||||
|
||||
pub fn database_exists<'a>(&self, url: &'a str) -> BoxFuture<'a, crate::Result<bool>> {
|
||||
(self.database_exists)(url)
|
||||
}
|
||||
|
||||
pub fn drop_database<'a>(&self, url: &'a str) -> BoxFuture<'a, crate::Result<()>> {
|
||||
(self.drop_database)(url)
|
||||
}
|
||||
|
||||
pub fn force_drop_database<'a>(&self, url: &'a str) -> BoxFuture<'a, crate::Result<()>> {
|
||||
(self.force_drop_database)(url)
|
||||
}
|
||||
}
|
||||
|
||||
/// Install the list of drivers for [`AnyConnection`] to use.
|
||||
///
|
||||
/// Must be called before an `AnyConnection` or `AnyPool` can be connected.
|
||||
///
|
||||
/// ### Errors
|
||||
/// If called more than once.
|
||||
pub fn install_drivers(
|
||||
drivers: &'static [AnyDriver],
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
|
||||
DRIVERS
|
||||
.set(drivers)
|
||||
.map_err(|_| "drivers already installed".into())
|
||||
}
|
||||
|
||||
#[cfg(feature = "migrate")]
|
||||
pub(crate) fn from_url_str(url: &str) -> crate::Result<&'static AnyDriver> {
|
||||
from_url(&url.parse().map_err(Error::config)?)
|
||||
}
|
||||
|
||||
pub(crate) fn from_url(url: &Url) -> crate::Result<&'static AnyDriver> {
|
||||
let scheme = url.scheme();
|
||||
|
||||
let drivers: &[AnyDriver] = DRIVERS
|
||||
.get()
|
||||
.expect("No drivers installed. Please see the documentation in `sqlx::any` for details.");
|
||||
|
||||
drivers
|
||||
.iter()
|
||||
.find(|driver| driver.url_schemes.contains(&url.scheme()))
|
||||
.ok_or_else(|| {
|
||||
Error::Configuration(format!("no driver found for URL scheme {scheme:?}").into())
|
||||
})
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
use std::any::type_name;
|
||||
|
||||
use crate::any::type_info::AnyTypeInfo;
|
||||
use crate::any::Any;
|
||||
use crate::error::BoxDynError;
|
||||
use crate::type_info::TypeInfo;
|
||||
use crate::types::Type;
|
||||
|
||||
pub(super) fn mismatched_types<T: Type<Any>>(ty: &AnyTypeInfo) -> BoxDynError {
|
||||
format!(
|
||||
"mismatched types; Rust type `{}` is not compatible with SQL type `{}`",
|
||||
type_name::<T>(),
|
||||
ty.name()
|
||||
)
|
||||
.into()
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
// Annoying how deprecation warnings trigger in the same module as the deprecated item.
|
||||
#![allow(deprecated)]
|
||||
// Cargo features are broken in this file.
|
||||
// `AnyKind` may return at some point but it won't be a simple enum.
|
||||
#![allow(unexpected_cfgs)]
|
||||
|
||||
use crate::error::Error;
|
||||
use std::str::FromStr;
|
||||
|
||||
#[deprecated = "not used or returned by any API"]
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
|
||||
pub enum AnyKind {
|
||||
#[cfg(feature = "postgres")]
|
||||
Postgres,
|
||||
|
||||
#[cfg(feature = "mysql")]
|
||||
MySql,
|
||||
|
||||
#[cfg(feature = "_sqlite")]
|
||||
Sqlite,
|
||||
|
||||
#[cfg(feature = "mssql")]
|
||||
Mssql,
|
||||
}
|
||||
|
||||
impl FromStr for AnyKind {
|
||||
type Err = Error;
|
||||
|
||||
fn from_str(url: &str) -> Result<Self, Self::Err> {
|
||||
match url {
|
||||
#[cfg(feature = "postgres")]
|
||||
_ if url.starts_with("postgres:") || url.starts_with("postgresql:") => {
|
||||
Ok(AnyKind::Postgres)
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "postgres"))]
|
||||
_ if url.starts_with("postgres:") || url.starts_with("postgresql:") => {
|
||||
Err(Error::Configuration("database URL has the scheme of a PostgreSQL database but the `postgres` feature is not enabled".into()))
|
||||
}
|
||||
|
||||
#[cfg(feature = "mysql")]
|
||||
_ if url.starts_with("mysql:") || url.starts_with("mariadb:") => {
|
||||
Ok(AnyKind::MySql)
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "mysql"))]
|
||||
_ if url.starts_with("mysql:") || url.starts_with("mariadb:") => {
|
||||
Err(Error::Configuration("database URL has the scheme of a MySQL database but the `mysql` feature is not enabled".into()))
|
||||
}
|
||||
|
||||
#[cfg(feature = "_sqlite")]
|
||||
_ if url.starts_with("sqlite:") => {
|
||||
Ok(AnyKind::Sqlite)
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "_sqlite"))]
|
||||
_ if url.starts_with("sqlite:") => {
|
||||
Err(Error::Configuration("database URL has the scheme of a SQLite database but the `sqlite` feature is not enabled".into()))
|
||||
}
|
||||
|
||||
#[cfg(feature = "mssql")]
|
||||
_ if url.starts_with("mssql:") || url.starts_with("sqlserver:") => {
|
||||
Ok(AnyKind::Mssql)
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "mssql"))]
|
||||
_ if url.starts_with("mssql:") || url.starts_with("sqlserver:") => {
|
||||
Err(Error::Configuration("database URL has the scheme of a MSSQL database but the `mssql` feature is not enabled".into()))
|
||||
}
|
||||
|
||||
_ => Err(Error::Configuration(format!("unrecognized database url: {url:?}").into()))
|
||||
}
|
||||
}
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
use crate::any::driver;
|
||||
use crate::any::{Any, AnyConnection};
|
||||
use crate::error::Error;
|
||||
use crate::migrate::{AppliedMigration, Migrate, MigrateDatabase, MigrateError, Migration};
|
||||
use futures_core::future::BoxFuture;
|
||||
use std::time::Duration;
|
||||
|
||||
impl MigrateDatabase for Any {
|
||||
async fn create_database(url: &str) -> Result<(), Error> {
|
||||
driver::from_url_str(url)?
|
||||
.get_migrate_database()?
|
||||
.create_database(url)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn database_exists(url: &str) -> Result<bool, Error> {
|
||||
driver::from_url_str(url)?
|
||||
.get_migrate_database()?
|
||||
.database_exists(url)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn drop_database(url: &str) -> Result<(), Error> {
|
||||
driver::from_url_str(url)?
|
||||
.get_migrate_database()?
|
||||
.drop_database(url)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn force_drop_database(url: &str) -> Result<(), Error> {
|
||||
driver::from_url_str(url)?
|
||||
.get_migrate_database()?
|
||||
.force_drop_database(url)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
impl Migrate for AnyConnection {
|
||||
fn create_schema_if_not_exists<'e>(
|
||||
&'e mut self,
|
||||
schema_name: &'e str,
|
||||
) -> BoxFuture<'e, Result<(), MigrateError>> {
|
||||
Box::pin(async {
|
||||
self.get_migrate()?
|
||||
.create_schema_if_not_exists(schema_name)
|
||||
.await
|
||||
})
|
||||
}
|
||||
|
||||
fn ensure_migrations_table<'e>(
|
||||
&'e mut self,
|
||||
table_name: &'e str,
|
||||
) -> BoxFuture<'e, Result<(), MigrateError>> {
|
||||
Box::pin(async {
|
||||
self.get_migrate()?
|
||||
.ensure_migrations_table(table_name)
|
||||
.await
|
||||
})
|
||||
}
|
||||
|
||||
fn dirty_version<'e>(
|
||||
&'e mut self,
|
||||
table_name: &'e str,
|
||||
) -> BoxFuture<'e, Result<Option<i64>, MigrateError>> {
|
||||
Box::pin(async { self.get_migrate()?.dirty_version(table_name).await })
|
||||
}
|
||||
|
||||
fn list_applied_migrations<'e>(
|
||||
&'e mut self,
|
||||
table_name: &'e str,
|
||||
) -> BoxFuture<'e, Result<Vec<AppliedMigration>, MigrateError>> {
|
||||
Box::pin(async {
|
||||
self.get_migrate()?
|
||||
.list_applied_migrations(table_name)
|
||||
.await
|
||||
})
|
||||
}
|
||||
|
||||
fn lock(&mut self) -> BoxFuture<'_, Result<(), MigrateError>> {
|
||||
Box::pin(async { self.get_migrate()?.lock().await })
|
||||
}
|
||||
|
||||
fn unlock(&mut self) -> BoxFuture<'_, Result<(), MigrateError>> {
|
||||
Box::pin(async { self.get_migrate()?.unlock().await })
|
||||
}
|
||||
|
||||
fn apply<'e>(
|
||||
&'e mut self,
|
||||
table_name: &'e str,
|
||||
migration: &'e Migration,
|
||||
) -> BoxFuture<'e, Result<Duration, MigrateError>> {
|
||||
Box::pin(async { self.get_migrate()?.apply(table_name, migration).await })
|
||||
}
|
||||
|
||||
fn revert<'e>(
|
||||
&'e mut self,
|
||||
table_name: &'e str,
|
||||
migration: &'e Migration,
|
||||
) -> BoxFuture<'e, Result<Duration, MigrateError>> {
|
||||
Box::pin(async { self.get_migrate()?.revert(table_name, migration).await })
|
||||
}
|
||||
|
||||
fn skip<'e>(
|
||||
&'e mut self,
|
||||
table_name: &'e str,
|
||||
migration: &'e Migration,
|
||||
) -> BoxFuture<'e, Result<(), MigrateError>> {
|
||||
Box::pin(async { self.get_migrate()?.skip(table_name, migration).await })
|
||||
}
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
//! **SEE DOCUMENTATION BEFORE USE**. Generic database driver with the specific driver selected at runtime.
|
||||
//!
|
||||
//! The underlying database drivers are chosen at runtime from the list set via
|
||||
//! [`install_drivers`][self::driver::install_drivers]. Any use of `AnyConnection` or `AnyPool`
|
||||
//! without this will panic.
|
||||
use crate::executor::Executor;
|
||||
|
||||
mod arguments;
|
||||
pub(crate) mod column;
|
||||
mod connection;
|
||||
mod database;
|
||||
mod error;
|
||||
mod kind;
|
||||
mod options;
|
||||
mod query_result;
|
||||
pub(crate) mod row;
|
||||
mod statement;
|
||||
mod transaction;
|
||||
pub(crate) mod type_info;
|
||||
pub mod types;
|
||||
pub(crate) mod value;
|
||||
|
||||
pub mod driver;
|
||||
|
||||
#[cfg(feature = "migrate")]
|
||||
mod migrate;
|
||||
|
||||
pub use arguments::{AnyArgumentBuffer, AnyArguments};
|
||||
pub use column::AnyColumn;
|
||||
pub use connection::AnyConnection;
|
||||
// Used internally in `sqlx-macros`
|
||||
|
||||
use crate::encode::Encode;
|
||||
pub use connection::AnyConnectionBackend;
|
||||
pub use database::Any;
|
||||
#[allow(deprecated)]
|
||||
pub use kind::AnyKind;
|
||||
pub use options::AnyConnectOptions;
|
||||
pub use query_result::AnyQueryResult;
|
||||
pub use row::AnyRow;
|
||||
pub use statement::AnyStatement;
|
||||
pub use transaction::AnyTransactionManager;
|
||||
pub use type_info::{AnyTypeInfo, AnyTypeInfoKind};
|
||||
pub use value::{AnyValue, AnyValueRef};
|
||||
|
||||
use crate::types::Type;
|
||||
#[doc(hidden)]
|
||||
pub use value::AnyValueKind;
|
||||
|
||||
pub type AnyPool = crate::pool::Pool<Any>;
|
||||
|
||||
pub type AnyPoolOptions = crate::pool::PoolOptions<Any>;
|
||||
|
||||
/// An alias for [`Executor<'_, Database = Any>`][Executor].
|
||||
pub trait AnyExecutor<'c>: Executor<'c, Database = Any> {}
|
||||
impl<'c, T: Executor<'c, Database = Any>> AnyExecutor<'c> for T {}
|
||||
|
||||
// NOTE: required due to the lack of lazy normalization
|
||||
impl_into_arguments_for_arguments!(AnyArguments);
|
||||
// impl_executor_for_pool_connection!(Any, AnyConnection, AnyRow);
|
||||
// impl_executor_for_transaction!(Any, AnyRow);
|
||||
impl_acquire!(Any, AnyConnection);
|
||||
impl_column_index_for_row!(AnyRow);
|
||||
impl_column_index_for_statement!(AnyStatement);
|
||||
// impl_into_maybe_pool!(Any, AnyConnection);
|
||||
|
||||
// required because some databases have a different handling of NULL
|
||||
impl<'q, T> Encode<'q, Any> for Option<T>
|
||||
where
|
||||
T: Encode<'q, Any> + 'q + Type<Any>,
|
||||
{
|
||||
fn encode_by_ref(
|
||||
&self,
|
||||
buf: &mut AnyArgumentBuffer,
|
||||
) -> Result<crate::encode::IsNull, crate::error::BoxDynError> {
|
||||
if let Some(value) = self {
|
||||
value.encode_by_ref(buf)
|
||||
} else {
|
||||
buf.0.push(AnyValueKind::Null(T::type_info().kind));
|
||||
Ok(crate::encode::IsNull::Yes)
|
||||
}
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
use crate::any::AnyConnection;
|
||||
use crate::connection::{ConnectOptions, LogSettings};
|
||||
use crate::error::Error;
|
||||
use log::LevelFilter;
|
||||
use std::future::Future;
|
||||
use std::str::FromStr;
|
||||
use std::time::Duration;
|
||||
use url::Url;
|
||||
|
||||
/// Opaque options for connecting to a database. These may only be constructed by parsing from
|
||||
/// a connection url.
|
||||
///
|
||||
/// ```text
|
||||
/// postgres://postgres:password@localhost/database
|
||||
/// mysql://root:password@localhost/database
|
||||
/// ```
|
||||
#[derive(Debug, Clone)]
|
||||
#[non_exhaustive]
|
||||
pub struct AnyConnectOptions {
|
||||
pub database_url: Url,
|
||||
pub log_settings: LogSettings,
|
||||
}
|
||||
impl FromStr for AnyConnectOptions {
|
||||
type Err = Error;
|
||||
|
||||
fn from_str(url: &str) -> Result<Self, Self::Err> {
|
||||
Ok(AnyConnectOptions {
|
||||
database_url: url
|
||||
.parse::<Url>()
|
||||
.map_err(|e| Error::Configuration(e.into()))?,
|
||||
log_settings: LogSettings::default(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ConnectOptions for AnyConnectOptions {
|
||||
type Connection = AnyConnection;
|
||||
|
||||
fn from_url(url: &Url) -> Result<Self, Error> {
|
||||
Ok(AnyConnectOptions {
|
||||
database_url: url.clone(),
|
||||
log_settings: LogSettings::default(),
|
||||
})
|
||||
}
|
||||
|
||||
fn to_url_lossy(&self) -> Url {
|
||||
self.database_url.clone()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn connect(&self) -> impl Future<Output = Result<AnyConnection, Error>> + Send + '_ {
|
||||
AnyConnection::connect(self)
|
||||
}
|
||||
|
||||
fn log_statements(mut self, level: LevelFilter) -> Self {
|
||||
self.log_settings.statements_level = level;
|
||||
self
|
||||
}
|
||||
|
||||
fn log_slow_statements(mut self, level: LevelFilter, duration: Duration) -> Self {
|
||||
self.log_settings.slow_statements_level = level;
|
||||
self.log_settings.slow_statements_duration = duration;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl AnyConnectOptions {}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
use std::iter::{Extend, IntoIterator};
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct AnyQueryResult {
|
||||
#[doc(hidden)]
|
||||
pub rows_affected: u64,
|
||||
#[doc(hidden)]
|
||||
pub last_insert_id: Option<i64>,
|
||||
}
|
||||
|
||||
impl AnyQueryResult {
|
||||
pub fn rows_affected(&self) -> u64 {
|
||||
self.rows_affected
|
||||
}
|
||||
|
||||
pub fn last_insert_id(&self) -> Option<i64> {
|
||||
self.last_insert_id
|
||||
}
|
||||
}
|
||||
|
||||
impl Extend<AnyQueryResult> for AnyQueryResult {
|
||||
fn extend<T: IntoIterator<Item = AnyQueryResult>>(&mut self, iter: T) {
|
||||
for elem in iter {
|
||||
self.rows_affected += elem.rows_affected;
|
||||
self.last_insert_id = elem.last_insert_id;
|
||||
}
|
||||
}
|
||||
}
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
use crate::any::error::mismatched_types;
|
||||
use crate::any::{Any, AnyColumn, AnyTypeInfo, AnyTypeInfoKind, AnyValue, AnyValueKind};
|
||||
use crate::column::{Column, ColumnIndex};
|
||||
use crate::database::Database;
|
||||
use crate::decode::Decode;
|
||||
use crate::error::Error;
|
||||
use crate::ext::ustr::UStr;
|
||||
use crate::row::Row;
|
||||
use crate::type_info::TypeInfo;
|
||||
use crate::types::Type;
|
||||
use crate::value::{Value, ValueRef};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AnyRow {
|
||||
#[doc(hidden)]
|
||||
pub column_names: Arc<crate::HashMap<UStr, usize>>,
|
||||
#[doc(hidden)]
|
||||
pub columns: Vec<AnyColumn>,
|
||||
#[doc(hidden)]
|
||||
pub values: Vec<AnyValue>,
|
||||
}
|
||||
|
||||
impl Row for AnyRow {
|
||||
type Database = Any;
|
||||
|
||||
fn columns(&self) -> &[AnyColumn] {
|
||||
&self.columns
|
||||
}
|
||||
|
||||
fn try_get_raw<I>(&self, index: I) -> Result<<Self::Database as Database>::ValueRef<'_>, Error>
|
||||
where
|
||||
I: ColumnIndex<Self>,
|
||||
{
|
||||
let index = index.index(self)?;
|
||||
Ok(self
|
||||
.values
|
||||
.get(index)
|
||||
.ok_or_else(|| Error::ColumnIndexOutOfBounds {
|
||||
index,
|
||||
len: self.columns.len(),
|
||||
})?
|
||||
.as_ref())
|
||||
}
|
||||
|
||||
fn try_get<'r, T, I>(&'r self, index: I) -> Result<T, Error>
|
||||
where
|
||||
I: ColumnIndex<Self>,
|
||||
T: Decode<'r, Self::Database> + Type<Self::Database>,
|
||||
{
|
||||
let value = self.try_get_raw(&index)?;
|
||||
let ty = value.type_info();
|
||||
|
||||
if !value.is_null() && !ty.is_null() && !T::compatible(&ty) {
|
||||
Err(mismatched_types::<T>(&ty))
|
||||
} else {
|
||||
T::decode(value)
|
||||
}
|
||||
.map_err(|source| Error::ColumnDecode {
|
||||
index: format!("{index:?}"),
|
||||
source,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ColumnIndex<AnyRow> for &'_ str {
|
||||
fn index(&self, row: &AnyRow) -> Result<usize, Error> {
|
||||
row.column_names
|
||||
.get(*self)
|
||||
.copied()
|
||||
.ok_or_else(|| Error::ColumnNotFound(self.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
impl AnyRow {
|
||||
// This is not a `TryFrom` impl because trait impls are easy for users to accidentally
|
||||
// become reliant upon, even if hidden, but we want to be able to change the bounds
|
||||
// on this function as the `Any` driver gains support for more types.
|
||||
//
|
||||
// Also `column_names` needs to be passed by the driver to avoid making deep copies.
|
||||
#[doc(hidden)]
|
||||
pub fn map_from<'a, R: Row>(
|
||||
row: &'a R,
|
||||
column_names: Arc<crate::HashMap<UStr, usize>>,
|
||||
) -> Result<Self, Error>
|
||||
where
|
||||
usize: ColumnIndex<R>,
|
||||
AnyTypeInfo: for<'b> TryFrom<&'b <R::Database as Database>::TypeInfo, Error = Error>,
|
||||
AnyColumn: for<'b> TryFrom<&'b <R::Database as Database>::Column, Error = Error>,
|
||||
bool: Type<R::Database> + Decode<'a, R::Database>,
|
||||
i16: Type<R::Database> + Decode<'a, R::Database>,
|
||||
i32: Type<R::Database> + Decode<'a, R::Database>,
|
||||
i64: Type<R::Database> + Decode<'a, R::Database>,
|
||||
f32: Type<R::Database> + Decode<'a, R::Database>,
|
||||
f64: Type<R::Database> + Decode<'a, R::Database>,
|
||||
String: Type<R::Database> + Decode<'a, R::Database>,
|
||||
Vec<u8>: Type<R::Database> + Decode<'a, R::Database>,
|
||||
{
|
||||
let mut row_out = AnyRow {
|
||||
column_names,
|
||||
columns: Vec::with_capacity(row.columns().len()),
|
||||
values: Vec::with_capacity(row.columns().len()),
|
||||
};
|
||||
|
||||
for col in row.columns() {
|
||||
let i = col.ordinal();
|
||||
|
||||
let any_col = AnyColumn::try_from(col)?;
|
||||
|
||||
let value = row.try_get_raw(i)?;
|
||||
|
||||
// Map based on the _value_ type info, not the column type info.
|
||||
let type_info =
|
||||
AnyTypeInfo::try_from(&value.type_info()).map_err(|e| Error::ColumnDecode {
|
||||
index: col.ordinal().to_string(),
|
||||
source: e.into(),
|
||||
})?;
|
||||
|
||||
let value_kind = match type_info.kind {
|
||||
k if value.is_null() => AnyValueKind::Null(k),
|
||||
AnyTypeInfoKind::Null => AnyValueKind::Null(AnyTypeInfoKind::Null),
|
||||
AnyTypeInfoKind::Bool => AnyValueKind::Bool(decode(value)?),
|
||||
AnyTypeInfoKind::SmallInt => AnyValueKind::SmallInt(decode(value)?),
|
||||
AnyTypeInfoKind::Integer => AnyValueKind::Integer(decode(value)?),
|
||||
AnyTypeInfoKind::BigInt => AnyValueKind::BigInt(decode(value)?),
|
||||
AnyTypeInfoKind::Real => AnyValueKind::Real(decode(value)?),
|
||||
AnyTypeInfoKind::Double => AnyValueKind::Double(decode(value)?),
|
||||
AnyTypeInfoKind::Blob => AnyValueKind::Blob(decode::<_, Vec<u8>>(value)?.into()),
|
||||
AnyTypeInfoKind::Text => AnyValueKind::Text(decode::<_, String>(value)?.into()),
|
||||
};
|
||||
|
||||
row_out.columns.push(any_col);
|
||||
row_out.values.push(AnyValue { kind: value_kind });
|
||||
}
|
||||
|
||||
Ok(row_out)
|
||||
}
|
||||
}
|
||||
|
||||
fn decode<'r, DB: Database, T: Decode<'r, DB>>(
|
||||
valueref: <DB as Database>::ValueRef<'r>,
|
||||
) -> crate::Result<T> {
|
||||
Decode::decode(valueref).map_err(Error::decode)
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
use crate::any::{Any, AnyArguments, AnyColumn, AnyTypeInfo};
|
||||
use crate::column::ColumnIndex;
|
||||
use crate::database::Database;
|
||||
use crate::error::Error;
|
||||
use crate::ext::ustr::UStr;
|
||||
use crate::sql_str::SqlStr;
|
||||
use crate::statement::Statement;
|
||||
use crate::HashMap;
|
||||
use either::Either;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AnyStatement {
|
||||
#[doc(hidden)]
|
||||
pub sql: SqlStr,
|
||||
#[doc(hidden)]
|
||||
pub parameters: Option<Either<Vec<AnyTypeInfo>, usize>>,
|
||||
#[doc(hidden)]
|
||||
pub column_names: Arc<HashMap<UStr, usize>>,
|
||||
#[doc(hidden)]
|
||||
pub columns: Vec<AnyColumn>,
|
||||
}
|
||||
|
||||
impl Statement for AnyStatement {
|
||||
type Database = Any;
|
||||
|
||||
fn into_sql(self) -> SqlStr {
|
||||
self.sql
|
||||
}
|
||||
|
||||
fn sql(&self) -> &SqlStr {
|
||||
&self.sql
|
||||
}
|
||||
|
||||
fn parameters(&self) -> Option<Either<&[AnyTypeInfo], usize>> {
|
||||
match &self.parameters {
|
||||
Some(Either::Left(types)) => Some(Either::Left(types)),
|
||||
Some(Either::Right(count)) => Some(Either::Right(*count)),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn columns(&self) -> &[AnyColumn] {
|
||||
&self.columns
|
||||
}
|
||||
|
||||
impl_statement_query!(AnyArguments);
|
||||
}
|
||||
|
||||
impl ColumnIndex<AnyStatement> for &'_ str {
|
||||
fn index(&self, statement: &AnyStatement) -> Result<usize, Error> {
|
||||
statement
|
||||
.column_names
|
||||
.get(*self)
|
||||
.ok_or_else(|| Error::ColumnNotFound((*self).into()))
|
||||
.copied()
|
||||
}
|
||||
}
|
||||
|
||||
impl AnyStatement {
|
||||
#[doc(hidden)]
|
||||
pub fn try_from_statement<S>(
|
||||
statement: S,
|
||||
column_names: Arc<HashMap<UStr, usize>>,
|
||||
) -> crate::Result<Self>
|
||||
where
|
||||
S: Statement,
|
||||
AnyTypeInfo: for<'a> TryFrom<&'a <S::Database as Database>::TypeInfo, Error = Error>,
|
||||
AnyColumn: for<'a> TryFrom<&'a <S::Database as Database>::Column, Error = Error>,
|
||||
{
|
||||
let parameters = match statement.parameters() {
|
||||
Some(Either::Left(parameters)) => Some(Either::Left(
|
||||
parameters
|
||||
.iter()
|
||||
.map(AnyTypeInfo::try_from)
|
||||
.collect::<Result<Vec<_>, _>>()?,
|
||||
)),
|
||||
Some(Either::Right(count)) => Some(Either::Right(count)),
|
||||
None => None,
|
||||
};
|
||||
|
||||
let columns = statement
|
||||
.columns()
|
||||
.iter()
|
||||
.map(AnyColumn::try_from)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
Ok(Self {
|
||||
sql: statement.into_sql(),
|
||||
columns,
|
||||
column_names,
|
||||
parameters,
|
||||
})
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
use std::future::Future;
|
||||
|
||||
use crate::any::{Any, AnyConnection};
|
||||
use crate::database::Database;
|
||||
use crate::error::Error;
|
||||
use crate::sql_str::SqlStr;
|
||||
use crate::transaction::TransactionManager;
|
||||
|
||||
pub struct AnyTransactionManager;
|
||||
|
||||
impl TransactionManager for AnyTransactionManager {
|
||||
type Database = Any;
|
||||
|
||||
fn begin(
|
||||
conn: &mut AnyConnection,
|
||||
statement: Option<SqlStr>,
|
||||
) -> impl Future<Output = Result<(), Error>> + Send + '_ {
|
||||
conn.backend.begin(statement)
|
||||
}
|
||||
|
||||
fn commit(conn: &mut AnyConnection) -> impl Future<Output = Result<(), Error>> + Send + '_ {
|
||||
conn.backend.commit()
|
||||
}
|
||||
|
||||
fn rollback(conn: &mut AnyConnection) -> impl Future<Output = Result<(), Error>> + Send + '_ {
|
||||
conn.backend.rollback()
|
||||
}
|
||||
|
||||
fn start_rollback(conn: &mut AnyConnection) {
|
||||
conn.backend.start_rollback()
|
||||
}
|
||||
|
||||
fn get_transaction_depth(conn: &<Self::Database as Database>::Connection) -> usize {
|
||||
conn.backend.get_transaction_depth()
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
use std::fmt::{self, Display, Formatter};
|
||||
|
||||
use crate::type_info::TypeInfo;
|
||||
|
||||
use AnyTypeInfoKind::*;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct AnyTypeInfo {
|
||||
#[doc(hidden)]
|
||||
pub kind: AnyTypeInfoKind,
|
||||
}
|
||||
|
||||
impl AnyTypeInfo {
|
||||
pub fn kind(&self) -> AnyTypeInfoKind {
|
||||
self.kind
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AnyTypeInfoKind {
|
||||
Null,
|
||||
Bool,
|
||||
SmallInt,
|
||||
Integer,
|
||||
BigInt,
|
||||
Real,
|
||||
Double,
|
||||
Text,
|
||||
Blob,
|
||||
}
|
||||
|
||||
impl TypeInfo for AnyTypeInfo {
|
||||
fn is_null(&self) -> bool {
|
||||
self.kind == Null
|
||||
}
|
||||
|
||||
fn name(&self) -> &str {
|
||||
use AnyTypeInfoKind::*;
|
||||
|
||||
match self.kind {
|
||||
Bool => "BOOLEAN",
|
||||
SmallInt => "SMALLINT",
|
||||
Integer => "INTEGER",
|
||||
BigInt => "BIGINT",
|
||||
Real => "REAL",
|
||||
Double => "DOUBLE",
|
||||
Text => "TEXT",
|
||||
Blob => "BLOB",
|
||||
Null => "NULL",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for AnyTypeInfo {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(self.name())
|
||||
}
|
||||
}
|
||||
|
||||
impl AnyTypeInfoKind {
|
||||
pub fn is_integer(&self) -> bool {
|
||||
matches!(self, SmallInt | Integer | BigInt)
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
use crate::any::{Any, AnyTypeInfo, AnyTypeInfoKind, AnyValueKind};
|
||||
use crate::database::Database;
|
||||
use crate::decode::Decode;
|
||||
use crate::encode::{Encode, IsNull};
|
||||
use crate::error::BoxDynError;
|
||||
use crate::types::Type;
|
||||
use std::sync::Arc;
|
||||
|
||||
impl Type<Any> for [u8] {
|
||||
fn type_info() -> AnyTypeInfo {
|
||||
AnyTypeInfo {
|
||||
kind: AnyTypeInfoKind::Blob,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'q> Encode<'q, Any> for &'q [u8] {
|
||||
fn encode_by_ref(
|
||||
&self,
|
||||
buf: &mut <Any as Database>::ArgumentBuffer,
|
||||
) -> Result<IsNull, BoxDynError> {
|
||||
buf.0.push(AnyValueKind::Blob(Arc::new(self.to_vec())));
|
||||
Ok(IsNull::No)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'r> Decode<'r, Any> for &'r [u8] {
|
||||
fn decode(value: <Any as Database>::ValueRef<'r>) -> Result<Self, BoxDynError> {
|
||||
match value.kind {
|
||||
AnyValueKind::Blob(blob) => Ok(blob.as_slice()),
|
||||
other => other.unexpected(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Type<Any> for Vec<u8> {
|
||||
fn type_info() -> AnyTypeInfo {
|
||||
<[u8] as Type<Any>>::type_info()
|
||||
}
|
||||
}
|
||||
|
||||
impl Encode<'_, Any> for Vec<u8> {
|
||||
fn encode_by_ref(
|
||||
&self,
|
||||
buf: &mut <Any as Database>::ArgumentBuffer,
|
||||
) -> Result<IsNull, BoxDynError> {
|
||||
buf.0.push(AnyValueKind::Blob(Arc::new(self.clone())));
|
||||
Ok(IsNull::No)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'r> Decode<'r, Any> for Vec<u8> {
|
||||
fn decode(value: <Any as Database>::ValueRef<'r>) -> Result<Self, BoxDynError> {
|
||||
match value.kind {
|
||||
AnyValueKind::Blob(blob) => Ok(blob.as_ref().clone()),
|
||||
other => other.unexpected(),
|
||||
}
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
use crate::any::{Any, AnyTypeInfo, AnyTypeInfoKind, AnyValueKind};
|
||||
use crate::database::Database;
|
||||
use crate::decode::Decode;
|
||||
use crate::encode::{Encode, IsNull};
|
||||
use crate::error::BoxDynError;
|
||||
use crate::types::Type;
|
||||
|
||||
impl Type<Any> for bool {
|
||||
fn type_info() -> AnyTypeInfo {
|
||||
AnyTypeInfo {
|
||||
kind: AnyTypeInfoKind::Bool,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Encode<'_, Any> for bool {
|
||||
fn encode_by_ref(
|
||||
&self,
|
||||
buf: &mut <Any as Database>::ArgumentBuffer,
|
||||
) -> Result<IsNull, BoxDynError> {
|
||||
buf.0.push(AnyValueKind::Bool(*self));
|
||||
Ok(IsNull::No)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'r> Decode<'r, Any> for bool {
|
||||
fn decode(value: <Any as Database>::ValueRef<'r>) -> Result<Self, BoxDynError> {
|
||||
match value.kind {
|
||||
AnyValueKind::Bool(b) => Ok(*b),
|
||||
other => other.unexpected(),
|
||||
}
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
use crate::any::{Any, AnyArgumentBuffer, AnyTypeInfo, AnyTypeInfoKind, AnyValueKind, AnyValueRef};
|
||||
use crate::database::Database;
|
||||
use crate::decode::Decode;
|
||||
use crate::encode::{Encode, IsNull};
|
||||
use crate::error::BoxDynError;
|
||||
use crate::types::Type;
|
||||
|
||||
impl Type<Any> for f32 {
|
||||
fn type_info() -> AnyTypeInfo {
|
||||
AnyTypeInfo {
|
||||
kind: AnyTypeInfoKind::Real,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Encode<'_, Any> for f32 {
|
||||
fn encode_by_ref(&self, buf: &mut AnyArgumentBuffer) -> Result<IsNull, BoxDynError> {
|
||||
buf.0.push(AnyValueKind::Real(*self));
|
||||
Ok(IsNull::No)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'r> Decode<'r, Any> for f32 {
|
||||
fn decode(value: AnyValueRef<'r>) -> Result<Self, BoxDynError> {
|
||||
match value.kind {
|
||||
AnyValueKind::Real(r) => Ok(*r),
|
||||
other => other.unexpected(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Type<Any> for f64 {
|
||||
fn type_info() -> AnyTypeInfo {
|
||||
AnyTypeInfo {
|
||||
kind: AnyTypeInfoKind::Double,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Encode<'_, Any> for f64 {
|
||||
fn encode_by_ref(
|
||||
&self,
|
||||
buf: &mut <Any as Database>::ArgumentBuffer,
|
||||
) -> Result<IsNull, BoxDynError> {
|
||||
buf.0.push(AnyValueKind::Double(*self));
|
||||
Ok(IsNull::No)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'r> Decode<'r, Any> for f64 {
|
||||
fn decode(value: <Any as Database>::ValueRef<'r>) -> Result<Self, BoxDynError> {
|
||||
match value.kind {
|
||||
// Widening is safe
|
||||
AnyValueKind::Real(r) => Ok(*r as f64),
|
||||
AnyValueKind::Double(d) => Ok(*d),
|
||||
other => other.unexpected(),
|
||||
}
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
use crate::any::{Any, AnyTypeInfo, AnyTypeInfoKind, AnyValueKind};
|
||||
use crate::database::Database;
|
||||
use crate::decode::Decode;
|
||||
use crate::encode::{Encode, IsNull};
|
||||
use crate::error::BoxDynError;
|
||||
use crate::types::Type;
|
||||
|
||||
impl Type<Any> for i16 {
|
||||
fn type_info() -> AnyTypeInfo {
|
||||
AnyTypeInfo {
|
||||
kind: AnyTypeInfoKind::SmallInt,
|
||||
}
|
||||
}
|
||||
|
||||
fn compatible(ty: &AnyTypeInfo) -> bool {
|
||||
ty.kind().is_integer()
|
||||
}
|
||||
}
|
||||
|
||||
impl Encode<'_, Any> for i16 {
|
||||
fn encode_by_ref(
|
||||
&self,
|
||||
buf: &mut <Any as Database>::ArgumentBuffer,
|
||||
) -> Result<IsNull, BoxDynError> {
|
||||
buf.0.push(AnyValueKind::SmallInt(*self));
|
||||
Ok(IsNull::No)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'r> Decode<'r, Any> for i16 {
|
||||
fn decode(value: <Any as Database>::ValueRef<'r>) -> Result<Self, BoxDynError> {
|
||||
value.kind.try_integer()
|
||||
}
|
||||
}
|
||||
|
||||
impl Type<Any> for i32 {
|
||||
fn type_info() -> AnyTypeInfo {
|
||||
AnyTypeInfo {
|
||||
kind: AnyTypeInfoKind::Integer,
|
||||
}
|
||||
}
|
||||
|
||||
fn compatible(ty: &AnyTypeInfo) -> bool {
|
||||
ty.kind().is_integer()
|
||||
}
|
||||
}
|
||||
|
||||
impl Encode<'_, Any> for i32 {
|
||||
fn encode_by_ref(
|
||||
&self,
|
||||
buf: &mut <Any as Database>::ArgumentBuffer,
|
||||
) -> Result<IsNull, BoxDynError> {
|
||||
buf.0.push(AnyValueKind::Integer(*self));
|
||||
Ok(IsNull::No)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'r> Decode<'r, Any> for i32 {
|
||||
fn decode(value: <Any as Database>::ValueRef<'r>) -> Result<Self, BoxDynError> {
|
||||
value.kind.try_integer()
|
||||
}
|
||||
}
|
||||
|
||||
impl Type<Any> for i64 {
|
||||
fn type_info() -> AnyTypeInfo {
|
||||
AnyTypeInfo {
|
||||
kind: AnyTypeInfoKind::BigInt,
|
||||
}
|
||||
}
|
||||
|
||||
fn compatible(ty: &AnyTypeInfo) -> bool {
|
||||
ty.kind().is_integer()
|
||||
}
|
||||
}
|
||||
|
||||
impl Encode<'_, Any> for i64 {
|
||||
fn encode_by_ref(
|
||||
&self,
|
||||
buf: &mut <Any as Database>::ArgumentBuffer,
|
||||
) -> Result<IsNull, BoxDynError> {
|
||||
buf.0.push(AnyValueKind::BigInt(*self));
|
||||
Ok(IsNull::No)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'r> Decode<'r, Any> for i64 {
|
||||
fn decode(value: <Any as Database>::ValueRef<'r>) -> Result<Self, BoxDynError> {
|
||||
value.kind.try_integer()
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
//! Conversions between Rust and standard **SQL** types.
|
||||
//!
|
||||
//! # Types
|
||||
//!
|
||||
//! | Rust type | SQL type(s) |
|
||||
//! |---------------------------------------|------------------------------------------------------|
|
||||
//! | `bool` | BOOLEAN |
|
||||
//! | `i16` | SMALLINT |
|
||||
//! | `i32` | INT |
|
||||
//! | `i64` | BIGINT |
|
||||
//! | `f32` | FLOAT |
|
||||
//! | `f64` | DOUBLE |
|
||||
//! | `&str`, [`String`] | VARCHAR, CHAR, TEXT |
|
||||
//!
|
||||
//! # Nullable
|
||||
//!
|
||||
//! In addition, `Option<T>` is supported where `T` implements `Type`. An `Option<T>` represents
|
||||
//! a potentially `NULL` value from SQL.
|
||||
|
||||
mod blob;
|
||||
mod bool;
|
||||
mod float;
|
||||
mod int;
|
||||
mod str;
|
||||
|
||||
#[test]
|
||||
fn test_type_impls() {
|
||||
use crate::any::Any;
|
||||
use crate::decode::Decode;
|
||||
use crate::encode::Encode;
|
||||
use crate::types::Type;
|
||||
|
||||
fn has_type<T>()
|
||||
where
|
||||
T: Type<Any>,
|
||||
for<'a> T: Encode<'a, Any>,
|
||||
for<'a> T: Decode<'a, Any>,
|
||||
{
|
||||
}
|
||||
|
||||
has_type::<bool>();
|
||||
|
||||
has_type::<i16>();
|
||||
has_type::<i32>();
|
||||
has_type::<i64>();
|
||||
|
||||
has_type::<f32>();
|
||||
has_type::<f64>();
|
||||
|
||||
// These imply that there are also impls for the equivalent slice types.
|
||||
has_type::<Vec<u8>>();
|
||||
has_type::<String>();
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
use crate::any::types::str;
|
||||
use crate::any::{Any, AnyTypeInfo, AnyTypeInfoKind, AnyValueKind};
|
||||
use crate::database::Database;
|
||||
use crate::decode::Decode;
|
||||
use crate::encode::{Encode, IsNull};
|
||||
use crate::error::BoxDynError;
|
||||
use crate::types::Type;
|
||||
use std::sync::Arc;
|
||||
|
||||
impl Type<Any> for str {
|
||||
fn type_info() -> AnyTypeInfo {
|
||||
AnyTypeInfo {
|
||||
kind: AnyTypeInfoKind::Text,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Encode<'a, Any> for &'a str {
|
||||
fn encode(self, buf: &mut <Any as Database>::ArgumentBuffer) -> Result<IsNull, BoxDynError>
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
buf.0.push(AnyValueKind::Text(Arc::new(self.into())));
|
||||
Ok(IsNull::No)
|
||||
}
|
||||
|
||||
fn encode_by_ref(
|
||||
&self,
|
||||
buf: &mut <Any as Database>::ArgumentBuffer,
|
||||
) -> Result<IsNull, BoxDynError> {
|
||||
(*self).encode(buf)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Decode<'a, Any> for &'a str {
|
||||
fn decode(value: <Any as Database>::ValueRef<'a>) -> Result<Self, BoxDynError> {
|
||||
match value.kind {
|
||||
AnyValueKind::Text(text) => Ok(text.as_str()),
|
||||
other => other.unexpected(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Type<Any> for String {
|
||||
fn type_info() -> AnyTypeInfo {
|
||||
<str as Type<Any>>::type_info()
|
||||
}
|
||||
}
|
||||
|
||||
impl Encode<'_, Any> for String {
|
||||
fn encode(self, buf: &mut <Any as Database>::ArgumentBuffer) -> Result<IsNull, BoxDynError> {
|
||||
buf.0.push(AnyValueKind::Text(Arc::new(self)));
|
||||
Ok(IsNull::No)
|
||||
}
|
||||
|
||||
fn encode_by_ref(
|
||||
&self,
|
||||
buf: &mut <Any as Database>::ArgumentBuffer,
|
||||
) -> Result<IsNull, BoxDynError> {
|
||||
buf.0.push(AnyValueKind::Text(Arc::new(self.clone())));
|
||||
Ok(IsNull::No)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'r> Decode<'r, Any> for String {
|
||||
fn decode(value: <Any as Database>::ValueRef<'r>) -> Result<Self, BoxDynError> {
|
||||
match value.kind {
|
||||
AnyValueKind::Text(text) => Ok(text.to_string()),
|
||||
other => other.unexpected(),
|
||||
}
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
use crate::any::{Any, AnyTypeInfo, AnyTypeInfoKind};
|
||||
use crate::database::Database;
|
||||
use crate::error::BoxDynError;
|
||||
use crate::types::Type;
|
||||
use crate::value::{Value, ValueRef};
|
||||
use std::borrow::Cow;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
#[non_exhaustive]
|
||||
pub enum AnyValueKind {
|
||||
Null(AnyTypeInfoKind),
|
||||
Bool(bool),
|
||||
SmallInt(i16),
|
||||
Integer(i32),
|
||||
BigInt(i64),
|
||||
Real(f32),
|
||||
Double(f64),
|
||||
Text(Arc<String>),
|
||||
TextSlice(Arc<str>),
|
||||
Blob(Arc<Vec<u8>>),
|
||||
}
|
||||
|
||||
impl AnyValueKind {
|
||||
fn type_info(&self) -> AnyTypeInfo {
|
||||
AnyTypeInfo {
|
||||
kind: match self {
|
||||
AnyValueKind::Null(_) => AnyTypeInfoKind::Null,
|
||||
AnyValueKind::Bool(_) => AnyTypeInfoKind::Bool,
|
||||
AnyValueKind::SmallInt(_) => AnyTypeInfoKind::SmallInt,
|
||||
AnyValueKind::Integer(_) => AnyTypeInfoKind::Integer,
|
||||
AnyValueKind::BigInt(_) => AnyTypeInfoKind::BigInt,
|
||||
AnyValueKind::Real(_) => AnyTypeInfoKind::Real,
|
||||
AnyValueKind::Double(_) => AnyTypeInfoKind::Double,
|
||||
AnyValueKind::Text(_) => AnyTypeInfoKind::Text,
|
||||
AnyValueKind::TextSlice(_) => AnyTypeInfoKind::Text,
|
||||
AnyValueKind::Blob(_) => AnyTypeInfoKind::Blob,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::any) fn unexpected<Expected: Type<Any>>(&self) -> Result<Expected, BoxDynError> {
|
||||
Err(format!("expected {}, got {:?}", Expected::type_info(), self).into())
|
||||
}
|
||||
|
||||
pub(in crate::any) fn try_integer<T>(&self) -> Result<T, BoxDynError>
|
||||
where
|
||||
T: Type<Any> + TryFrom<i16> + TryFrom<i32> + TryFrom<i64>,
|
||||
BoxDynError: From<<T as TryFrom<i16>>::Error>,
|
||||
BoxDynError: From<<T as TryFrom<i32>>::Error>,
|
||||
BoxDynError: From<<T as TryFrom<i64>>::Error>,
|
||||
{
|
||||
Ok(match self {
|
||||
AnyValueKind::SmallInt(i) => (*i).try_into()?,
|
||||
AnyValueKind::Integer(i) => (*i).try_into()?,
|
||||
AnyValueKind::BigInt(i) => (*i).try_into()?,
|
||||
_ => return self.unexpected(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct AnyValue {
|
||||
#[doc(hidden)]
|
||||
pub kind: AnyValueKind,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct AnyValueRef<'a> {
|
||||
pub(crate) kind: &'a AnyValueKind,
|
||||
}
|
||||
|
||||
impl Value for AnyValue {
|
||||
type Database = Any;
|
||||
|
||||
fn as_ref(&self) -> <Self::Database as Database>::ValueRef<'_> {
|
||||
AnyValueRef { kind: &self.kind }
|
||||
}
|
||||
|
||||
fn type_info(&self) -> Cow<'_, <Self::Database as Database>::TypeInfo> {
|
||||
Cow::Owned(self.kind.type_info())
|
||||
}
|
||||
|
||||
fn is_null(&self) -> bool {
|
||||
matches!(self.kind, AnyValueKind::Null(_))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> ValueRef<'a> for AnyValueRef<'a> {
|
||||
type Database = Any;
|
||||
|
||||
fn to_owned(&self) -> <Self::Database as Database>::Value {
|
||||
AnyValue {
|
||||
kind: self.kind.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn type_info(&self) -> Cow<'_, <Self::Database as Database>::TypeInfo> {
|
||||
Cow::Owned(self.kind.type_info())
|
||||
}
|
||||
|
||||
fn is_null(&self) -> bool {
|
||||
matches!(self.kind, AnyValueKind::Null(_))
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
//! Types and traits for passing arguments to SQL queries.
|
||||
|
||||
use crate::database::Database;
|
||||
use crate::encode::Encode;
|
||||
use crate::error::BoxDynError;
|
||||
use crate::types::Type;
|
||||
use std::fmt::{self, Write};
|
||||
|
||||
/// A tuple of arguments to be sent to the database.
|
||||
// This lint is designed for general collections, but `Arguments` is not meant to be as such.
|
||||
#[allow(clippy::len_without_is_empty)]
|
||||
pub trait Arguments: Send + Sized + Default {
|
||||
type Database: Database;
|
||||
|
||||
/// Reserves the capacity for at least `additional` more values (of `size` total bytes) to
|
||||
/// be added to the arguments without a reallocation.
|
||||
fn reserve(&mut self, additional: usize, size: usize);
|
||||
|
||||
/// Add the value to the end of the arguments.
|
||||
fn add<'t, T>(&mut self, value: T) -> Result<(), BoxDynError>
|
||||
where
|
||||
T: Encode<'t, Self::Database> + Type<Self::Database>;
|
||||
|
||||
/// The number of arguments that were already added.
|
||||
fn len(&self) -> usize;
|
||||
|
||||
fn format_placeholder<W: Write>(&self, writer: &mut W) -> fmt::Result {
|
||||
writer.write_str("?")
|
||||
}
|
||||
}
|
||||
|
||||
pub trait IntoArguments<DB: Database>: Sized + Send {
|
||||
fn into_arguments(self) -> <DB as Database>::Arguments;
|
||||
}
|
||||
|
||||
// NOTE: required due to lack of lazy normalization
|
||||
#[macro_export]
|
||||
macro_rules! impl_into_arguments_for_arguments {
|
||||
($Arguments:path) => {
|
||||
impl
|
||||
$crate::arguments::IntoArguments<<$Arguments as $crate::arguments::Arguments>::Database>
|
||||
for $Arguments
|
||||
{
|
||||
fn into_arguments(self) -> $Arguments {
|
||||
self
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// used by the query macros to prevent supernumerary `.bind()` calls
|
||||
pub struct ImmutableArguments<DB: Database>(pub <DB as Database>::Arguments);
|
||||
|
||||
impl<DB: Database> IntoArguments<DB> for ImmutableArguments<DB> {
|
||||
fn into_arguments(self) -> <DB as Database>::Arguments {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
use crate::database::Database;
|
||||
use crate::error::Error;
|
||||
|
||||
use std::fmt::Debug;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub trait Column: 'static + Send + Sync + Debug {
|
||||
type Database: Database<Column = Self>;
|
||||
|
||||
/// Gets the column ordinal.
|
||||
///
|
||||
/// This can be used to unambiguously refer to this column within a row in case more than
|
||||
/// one column have the same name
|
||||
fn ordinal(&self) -> usize;
|
||||
|
||||
/// Gets the column name or alias.
|
||||
///
|
||||
/// The column name is unreliable (and can change between database minor versions) if this
|
||||
/// column is an expression that has not been aliased.
|
||||
fn name(&self) -> &str;
|
||||
|
||||
/// Gets the type information for the column.
|
||||
fn type_info(&self) -> &<Self::Database as Database>::TypeInfo;
|
||||
|
||||
/// If this column comes from a table, return the table and original column name.
|
||||
///
|
||||
/// Returns [`ColumnOrigin::Expression`] if the column is the result of an expression
|
||||
/// or else the source table could not be determined.
|
||||
///
|
||||
/// Returns [`ColumnOrigin::Unknown`] if the database driver does not have that information,
|
||||
/// or has not overridden this method.
|
||||
// This method returns an owned value instead of a reference,
|
||||
// to give the implementor more flexibility.
|
||||
fn origin(&self) -> ColumnOrigin {
|
||||
ColumnOrigin::Unknown
|
||||
}
|
||||
}
|
||||
|
||||
/// A [`Column`] that originates from a table.
|
||||
#[derive(Debug, Clone)]
|
||||
#[cfg_attr(feature = "offline", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct TableColumn {
|
||||
/// The name of the table (optionally schema-qualified) that the column comes from.
|
||||
pub table: Arc<str>,
|
||||
/// The original name of the column.
|
||||
pub name: Arc<str>,
|
||||
}
|
||||
|
||||
/// The possible statuses for our knowledge of the origin of a [`Column`].
|
||||
#[derive(Debug, Clone, Default)]
|
||||
#[cfg_attr(feature = "offline", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum ColumnOrigin {
|
||||
/// The column is known to originate from a table.
|
||||
///
|
||||
/// Included is the table name and original column name.
|
||||
Table(TableColumn),
|
||||
/// The column originates from an expression, or else its origin could not be determined.
|
||||
Expression,
|
||||
/// The database driver does not know the column origin at this time.
|
||||
///
|
||||
/// This may happen if:
|
||||
/// * The connection is in the middle of executing a query,
|
||||
/// and cannot query the catalog to fetch this information.
|
||||
/// * The connection does not have access to the database catalog.
|
||||
/// * The implementation of [`Column`] did not override [`Column::origin()`].
|
||||
#[default]
|
||||
Unknown,
|
||||
}
|
||||
|
||||
impl ColumnOrigin {
|
||||
/// Returns the true column origin, if known.
|
||||
pub fn table_column(&self) -> Option<&TableColumn> {
|
||||
if let Self::Table(table_column) = self {
|
||||
Some(table_column)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A type that can be used to index into a [`Row`] or [`Statement`].
|
||||
///
|
||||
/// The [`get`] and [`try_get`] methods of [`Row`] accept any type that implements `ColumnIndex`.
|
||||
/// This trait is implemented for strings which are used to look up a column by name, and for
|
||||
/// `usize` which is used as a positional index into the row.
|
||||
///
|
||||
/// *Caution*: The column index may differ between a [`Statement`] and a [`Row`] returned by the
|
||||
/// statement. This can happen with some databases if, for example, the schema changes between
|
||||
/// prepare and execute or if the database does not provide column information when the statement
|
||||
/// is prepared.
|
||||
///
|
||||
/// [`Row`]: crate::row::Row
|
||||
/// [`Statement`]: crate::statement::Statement
|
||||
/// [`get`]: crate::row::Row::get
|
||||
/// [`try_get`]: crate::row::Row::try_get
|
||||
///
|
||||
pub trait ColumnIndex<T: ?Sized>: Debug {
|
||||
/// Returns a valid positional index into the row or statement, [`ColumnIndexOutOfBounds`], or,
|
||||
/// [`ColumnNotFound`].
|
||||
///
|
||||
/// [`ColumnNotFound`]: Error::ColumnNotFound
|
||||
/// [`ColumnIndexOutOfBounds`]: Error::ColumnIndexOutOfBounds
|
||||
fn index(&self, container: &T) -> Result<usize, Error>;
|
||||
}
|
||||
|
||||
impl<T: ?Sized, I: ColumnIndex<T> + ?Sized> ColumnIndex<T> for &'_ I {
|
||||
#[inline]
|
||||
fn index(&self, row: &T) -> Result<usize, Error> {
|
||||
(**self).index(row)
|
||||
}
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! impl_column_index_for_row {
|
||||
($R:ident) => {
|
||||
impl $crate::column::ColumnIndex<$R> for usize {
|
||||
fn index(&self, row: &$R) -> Result<usize, $crate::error::Error> {
|
||||
let len = $crate::row::Row::len(row);
|
||||
|
||||
if *self >= len {
|
||||
return Err($crate::error::Error::ColumnIndexOutOfBounds { len, index: *self });
|
||||
}
|
||||
|
||||
Ok(*self)
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! impl_column_index_for_statement {
|
||||
($S:ident) => {
|
||||
impl $crate::column::ColumnIndex<$S> for usize {
|
||||
fn index(&self, statement: &$S) -> Result<usize, $crate::error::Error> {
|
||||
let len = $crate::statement::Statement::columns(statement).len();
|
||||
|
||||
if *self >= len {
|
||||
return Err($crate::error::Error::ColumnIndexOutOfBounds { len, index: *self });
|
||||
}
|
||||
|
||||
Ok(*self)
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
mod statement_cache;
|
||||
|
||||
pub use statement_cache::StatementCache;
|
||||
use std::fmt::{Debug, Formatter};
|
||||
use std::ops::{Deref, DerefMut};
|
||||
|
||||
/// A wrapper for `Fn`s that provides a debug impl that just says "Function"
|
||||
pub struct DebugFn<F: ?Sized>(pub F);
|
||||
|
||||
impl<F: ?Sized> Deref for DebugFn<F> {
|
||||
type Target = F;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<F: ?Sized> DerefMut for DebugFn<F> {
|
||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
||||
&mut self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<F: ?Sized> Debug for DebugFn<F> {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_tuple("Function").finish()
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
use hashlink::lru_cache::LruCache;
|
||||
|
||||
/// A cache for prepared statements. When full, the least recently used
|
||||
/// statement gets removed.
|
||||
#[derive(Debug)]
|
||||
pub struct StatementCache<T> {
|
||||
inner: LruCache<String, T>,
|
||||
}
|
||||
|
||||
impl<T> StatementCache<T> {
|
||||
/// Create a new cache with the given capacity.
|
||||
pub fn new(capacity: usize) -> Self {
|
||||
Self {
|
||||
inner: LruCache::new(capacity),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a mutable reference to the value corresponding to the given key
|
||||
/// in the cache, if any.
|
||||
pub fn get_mut(&mut self, k: &str) -> Option<&mut T> {
|
||||
self.inner.get_mut(k)
|
||||
}
|
||||
|
||||
/// Inserts a new statement to the cache, returning the least recently used
|
||||
/// statement id if the cache is full, or if inserting with an existing key,
|
||||
/// the replaced existing statement.
|
||||
pub fn insert(&mut self, k: &str, v: T) -> Option<T> {
|
||||
let mut lru_item = None;
|
||||
|
||||
if self.capacity() == self.len() && !self.contains_key(k) {
|
||||
lru_item = self.remove_lru();
|
||||
} else if self.contains_key(k) {
|
||||
lru_item = self.inner.remove(k);
|
||||
}
|
||||
|
||||
self.inner.insert(k.into(), v);
|
||||
|
||||
lru_item
|
||||
}
|
||||
|
||||
/// The number of statements in the cache.
|
||||
pub fn len(&self) -> usize {
|
||||
self.inner.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.inner.is_empty()
|
||||
}
|
||||
|
||||
/// Removes the least recently used item from the cache.
|
||||
pub fn remove_lru(&mut self) -> Option<T> {
|
||||
self.inner.remove_lru().map(|(_, v)| v)
|
||||
}
|
||||
|
||||
/// Clear all cached statements from the cache.
|
||||
pub fn clear(&mut self) {
|
||||
self.inner.clear();
|
||||
}
|
||||
|
||||
/// True if cache has a value for the given key.
|
||||
pub fn contains_key(&mut self, k: &str) -> bool {
|
||||
self.inner.contains_key(k)
|
||||
}
|
||||
|
||||
/// Returns the maximum number of statements the cache can hold.
|
||||
pub fn capacity(&self) -> usize {
|
||||
self.inner.capacity()
|
||||
}
|
||||
|
||||
/// Returns true if the cache capacity is more than 0.
|
||||
#[allow(dead_code)] // Only used for some `cfg`s
|
||||
pub fn is_enabled(&self) -> bool {
|
||||
self.capacity() > 0
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
/// Configuration shared by multiple components.
|
||||
#[derive(Debug, Default)]
|
||||
#[cfg_attr(
|
||||
feature = "sqlx-toml",
|
||||
derive(serde::Deserialize),
|
||||
serde(default, rename_all = "kebab-case", deny_unknown_fields)
|
||||
)]
|
||||
pub struct Config {
|
||||
/// Override the database URL environment variable.
|
||||
///
|
||||
/// This is used by both the macros and `sqlx-cli`.
|
||||
///
|
||||
/// Case-sensitive. Defaults to `DATABASE_URL`.
|
||||
///
|
||||
/// Example: Multi-Database Project
|
||||
/// -------
|
||||
/// You can use multiple databases in the same project by breaking it up into multiple crates,
|
||||
/// then using a different environment variable for each.
|
||||
///
|
||||
/// For example, with two crates in the workspace named `foo` and `bar`:
|
||||
///
|
||||
/// #### `foo/sqlx.toml`
|
||||
/// ```toml
|
||||
/// [common]
|
||||
/// database-url-var = "FOO_DATABASE_URL"
|
||||
/// ```
|
||||
///
|
||||
/// #### `bar/sqlx.toml`
|
||||
/// ```toml
|
||||
/// [common]
|
||||
/// database-url-var = "BAR_DATABASE_URL"
|
||||
/// ```
|
||||
///
|
||||
/// #### `.env`
|
||||
/// ```text
|
||||
/// FOO_DATABASE_URL=postgres://postgres@localhost:5432/foo
|
||||
/// BAR_DATABASE_URL=postgres://postgres@localhost:5432/bar
|
||||
/// ```
|
||||
///
|
||||
/// The query macros used in `foo` will use `FOO_DATABASE_URL`,
|
||||
/// and the ones used in `bar` will use `BAR_DATABASE_URL`.
|
||||
pub database_url_var: Option<String>,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn database_url_var(&self) -> &str {
|
||||
self.database_url_var.as_deref().unwrap_or("DATABASE_URL")
|
||||
}
|
||||
}
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
use std::error::Error;
|
||||
|
||||
/// Configuration for specific database drivers (**applies to macros and `sqlx-cli` only**).
|
||||
///
|
||||
/// # Note: Does Not Apply at Application Run-Time
|
||||
/// As of writing, these configuration parameters do *not* have any bearing on
|
||||
/// the runtime configuration of SQLx database drivers.
|
||||
///
|
||||
/// Any parameters which overlap with runtime configuration
|
||||
/// (e.g. [`drivers.sqlite.unsafe-load-extensions`][SqliteConfig::unsafe_load_extensions])
|
||||
/// _must_ be configured their normal ways at runtime (e.g. `SqliteConnectOptions::extension()`).
|
||||
///
|
||||
/// See the documentation of individual fields for details.
|
||||
#[derive(Debug, Default)]
|
||||
#[cfg_attr(
|
||||
feature = "sqlx-toml",
|
||||
derive(serde::Deserialize),
|
||||
serde(default, rename_all = "kebab-case", deny_unknown_fields)
|
||||
)]
|
||||
pub struct Config {
|
||||
/// Configuration for the MySQL database driver.
|
||||
///
|
||||
/// See [`MySqlConfig`] for details.
|
||||
pub mysql: MySqlConfig,
|
||||
|
||||
/// Configuration for the Postgres database driver.
|
||||
///
|
||||
/// See [`PgConfig`] for details.
|
||||
pub postgres: PgConfig,
|
||||
|
||||
/// Configuration for the SQLite database driver.
|
||||
///
|
||||
/// See [`SqliteConfig`] for details.
|
||||
pub sqlite: SqliteConfig,
|
||||
|
||||
/// Configuration for external database drivers.
|
||||
///
|
||||
/// See [`ExternalDriverConfig`] for details.
|
||||
pub external: ExternalDriverConfig,
|
||||
}
|
||||
|
||||
/// Configuration for the MySQL database driver.
|
||||
#[derive(Debug, Default)]
|
||||
#[cfg_attr(
|
||||
feature = "sqlx-toml",
|
||||
derive(serde::Deserialize),
|
||||
serde(default, rename_all = "kebab-case", deny_unknown_fields)
|
||||
)]
|
||||
pub struct MySqlConfig {
|
||||
// No fields implemented yet. This key is only used to validate parsing.
|
||||
}
|
||||
|
||||
/// Configuration for the Postgres database driver.
|
||||
#[derive(Debug, Default)]
|
||||
#[cfg_attr(
|
||||
feature = "sqlx-toml",
|
||||
derive(serde::Deserialize),
|
||||
serde(default, rename_all = "kebab-case", deny_unknown_fields)
|
||||
)]
|
||||
pub struct PgConfig {
|
||||
// No fields implemented yet. This key is only used to validate parsing.
|
||||
}
|
||||
|
||||
/// Configuration for the SQLite database driver.
|
||||
#[derive(Debug, Default)]
|
||||
#[cfg_attr(
|
||||
feature = "sqlx-toml",
|
||||
derive(serde::Deserialize),
|
||||
serde(default, rename_all = "kebab-case", deny_unknown_fields)
|
||||
)]
|
||||
pub struct SqliteConfig {
|
||||
/// Specify extensions to load, either by name or by path.
|
||||
///
|
||||
/// Paths should be relative to the workspace root.
|
||||
///
|
||||
/// See [Loading an Extension](https://www.sqlite.org/loadext.html#loading_an_extension)
|
||||
/// in the SQLite manual for details.
|
||||
///
|
||||
/// The `sqlite-load-extension` feature must be enabled and SQLite must be built
|
||||
/// _without_ [`SQLITE_OMIT_LOAD_EXTENSION`] enabled.
|
||||
///
|
||||
/// [`SQLITE_OMIT_LOAD_EXTENSION`]: https://www.sqlite.org/compile.html#omit_load_extension
|
||||
///
|
||||
/// # Note: Does Not Configure Runtime Extension Loading
|
||||
/// Extensions to be loaded at runtime *must* be separately configured with
|
||||
/// `SqliteConnectOptions::extension()` or `SqliteConnectOptions::extension_with_entrypoint()`.
|
||||
///
|
||||
/// # Safety
|
||||
/// This causes arbitrary DLLs on the filesystem to be loaded at execution time,
|
||||
/// which can easily result in undefined behavior, memory corruption,
|
||||
/// or exploitable vulnerabilities if misused.
|
||||
///
|
||||
/// It is not possible to provide a truly safe version of this API.
|
||||
///
|
||||
/// Use this field with care, and only load extensions that you trust.
|
||||
///
|
||||
/// # Example
|
||||
/// Load the `uuid` and `vsv` extensions from [`sqlean`](https://github.com/nalgeon/sqlean).
|
||||
///
|
||||
/// `sqlx.toml`:
|
||||
/// ```toml
|
||||
/// [common.drivers.sqlite]
|
||||
/// unsafe-load-extensions = ["uuid", "vsv"]
|
||||
/// ```
|
||||
pub unsafe_load_extensions: Vec<SqliteExtension>,
|
||||
}
|
||||
|
||||
/// Extension for the SQLite database driver.
|
||||
#[derive(Debug, PartialEq)]
|
||||
#[cfg_attr(
|
||||
feature = "sqlx-toml",
|
||||
derive(serde::Deserialize),
|
||||
serde(untagged, deny_unknown_fields)
|
||||
)]
|
||||
pub enum SqliteExtension {
|
||||
Path(String),
|
||||
PathWithEntrypoint { path: String, entrypoint: String },
|
||||
}
|
||||
|
||||
/// Configuration for external database drivers.
|
||||
#[derive(Debug, Default)]
|
||||
#[cfg_attr(feature = "sqlx-toml", derive(serde::Deserialize), serde(transparent))]
|
||||
pub struct ExternalDriverConfig {
|
||||
#[cfg(feature = "sqlx-toml")]
|
||||
by_name: std::collections::BTreeMap<String, toml::Table>,
|
||||
}
|
||||
|
||||
/// Type-erased [`toml::de::Error`].
|
||||
pub type TryParseError = Box<dyn Error + Send + Sync + 'static>;
|
||||
|
||||
impl ExternalDriverConfig {
|
||||
/// Try to parse the config for a given driver name, returning `Ok(None)` if it does not exist.
|
||||
#[cfg(feature = "sqlx-toml")]
|
||||
pub fn try_parse<T: serde::de::DeserializeOwned>(
|
||||
&self,
|
||||
name: &str,
|
||||
) -> Result<Option<T>, TryParseError> {
|
||||
let Some(config) = self.by_name.get(name) else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
// What's really baffling is that `toml` doesn't provide any way to deserialize
|
||||
// from a `&Table` or `&Value`, only owned variants, so cloning is unavoidable here.
|
||||
Ok(Some(config.clone().try_into()?))
|
||||
}
|
||||
|
||||
/// Try to parse the config for a given driver name, returning `Ok(None)` if it does not exist.
|
||||
#[cfg(not(feature = "sqlx-toml"))]
|
||||
pub fn try_parse<T>(&self, _name: &str) -> Result<Option<T>, TryParseError> {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
+418
@@ -0,0 +1,418 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// Configuration for the `query!()` family of macros.
|
||||
///
|
||||
/// See also [`common::Config`][crate::config::common::Config] for renaming `DATABASE_URL`.
|
||||
#[derive(Debug, Default)]
|
||||
#[cfg_attr(
|
||||
feature = "sqlx-toml",
|
||||
derive(serde::Deserialize),
|
||||
serde(default, rename_all = "kebab-case", deny_unknown_fields)
|
||||
)]
|
||||
pub struct Config {
|
||||
/// Specify which crates' types to use when types from multiple crates apply.
|
||||
///
|
||||
/// See [`PreferredCrates`] for details.
|
||||
pub preferred_crates: PreferredCrates,
|
||||
|
||||
/// Specify global overrides for mapping SQL type names to Rust type names.
|
||||
///
|
||||
/// Default type mappings are defined by the database driver.
|
||||
/// Refer to the `sqlx::types` module for details.
|
||||
///
|
||||
/// ## Note: Case-Sensitive
|
||||
/// Currently, the case of the type name MUST match the name SQLx knows it by.
|
||||
/// Built-in types are spelled in all-uppercase to match SQL convention.
|
||||
///
|
||||
/// However, user-created types in Postgres are all-lowercase unless quoted.
|
||||
///
|
||||
/// ## Note: Orthogonal to Nullability
|
||||
/// These overrides do not affect whether `query!()` decides to wrap a column in `Option<_>`
|
||||
/// or not. They only override the inner type used.
|
||||
///
|
||||
/// ## Note: Schema Qualification (Postgres)
|
||||
/// Type names may be schema-qualified in Postgres. If so, the schema should be part
|
||||
/// of the type string, e.g. `'foo.bar'` to reference type `bar` in schema `foo`.
|
||||
///
|
||||
/// The schema and/or type name may additionally be quoted in the string
|
||||
/// for a quoted identifier (see next section).
|
||||
///
|
||||
/// Schema qualification should not be used for types in the search path.
|
||||
///
|
||||
/// ## Note: Quoted Identifiers (Postgres)
|
||||
/// Type names using [quoted identifiers in Postgres] must also be specified with quotes here.
|
||||
///
|
||||
/// Note, however, that the TOML format parses way the outer pair of quotes,
|
||||
/// so for quoted names in Postgres, double-quoting is necessary,
|
||||
/// e.g. `'"Foo"'` for SQL type `"Foo"`.
|
||||
///
|
||||
/// To reference a schema-qualified type with a quoted name, use double-quotes after the
|
||||
/// dot, e.g. `'foo."Bar"'` to reference type `"Bar"` of schema `foo`, and vice versa for
|
||||
/// quoted schema names.
|
||||
///
|
||||
/// We recommend wrapping all type names in single quotes, as shown below,
|
||||
/// to avoid confusion.
|
||||
///
|
||||
/// MySQL/MariaDB and SQLite do not support custom types, so quoting type names should
|
||||
/// never be necessary.
|
||||
///
|
||||
/// [quoted identifiers in Postgres]: https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS
|
||||
// Note: we wanted to be able to handle this intelligently,
|
||||
// but the `toml` crate authors weren't interested: https://github.com/toml-rs/toml/issues/761
|
||||
//
|
||||
// We decided to just encourage always quoting type names instead.
|
||||
/// Example: Custom Wrapper Types
|
||||
/// -------
|
||||
/// Does SQLx not support a type that you need? Do you want additional semantics not
|
||||
/// implemented on the built-in types? You can create a custom wrapper,
|
||||
/// or use an external crate.
|
||||
///
|
||||
/// #### `sqlx.toml`
|
||||
/// ```toml
|
||||
/// [macros.type-overrides]
|
||||
/// # Override a built-in type
|
||||
/// 'UUID' = "crate::types::MyUuid"
|
||||
///
|
||||
/// # Support an external or custom wrapper type (e.g. from the `isn` Postgres extension)
|
||||
/// # (NOTE: FOR DOCUMENTATION PURPOSES ONLY; THIS CRATE/TYPE DOES NOT EXIST AS OF WRITING)
|
||||
/// 'isbn13' = "isn_rs::sqlx::ISBN13"
|
||||
/// ```
|
||||
///
|
||||
/// Example: Custom Types in Postgres
|
||||
/// -------
|
||||
/// If you have a custom type in Postgres that you want to map without needing to use
|
||||
/// the type override syntax in `sqlx::query!()` every time, you can specify a global
|
||||
/// override here.
|
||||
///
|
||||
/// For example, a custom enum type `foo`:
|
||||
///
|
||||
/// #### Migration or Setup SQL (e.g. `migrations/0_setup.sql`)
|
||||
/// ```sql
|
||||
/// CREATE TYPE foo AS ENUM ('Bar', 'Baz');
|
||||
/// ```
|
||||
///
|
||||
/// #### `src/types.rs`
|
||||
/// ```rust,no_run
|
||||
/// #[derive(sqlx::Type)]
|
||||
/// pub enum Foo {
|
||||
/// Bar,
|
||||
/// Baz
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// If you're not using `PascalCase` in your enum variants then you'll want to use
|
||||
/// `#[sqlx(rename_all = "<strategy>")]` on your enum.
|
||||
/// See [`Type`][crate::type::Type] for details.
|
||||
///
|
||||
/// #### `sqlx.toml`
|
||||
/// ```toml
|
||||
/// [macros.type-overrides]
|
||||
/// # Map SQL type `foo` to `crate::types::Foo`
|
||||
/// 'foo' = "crate::types::Foo"
|
||||
/// ```
|
||||
///
|
||||
/// Example: Schema-Qualified Types
|
||||
/// -------
|
||||
/// (See `Note` section above for details.)
|
||||
///
|
||||
/// ```toml
|
||||
/// [macros.type-overrides]
|
||||
/// # Map SQL type `foo.foo` to `crate::types::Foo`
|
||||
/// 'foo.foo' = "crate::types::Foo"
|
||||
/// ```
|
||||
///
|
||||
/// Example: Quoted Identifiers
|
||||
/// -------
|
||||
/// If a type or schema uses quoted identifiers,
|
||||
/// it must be wrapped in quotes _twice_ for SQLx to know the difference:
|
||||
///
|
||||
/// ```toml
|
||||
/// [macros.type-overrides]
|
||||
/// # `"Foo"` in SQLx
|
||||
/// '"Foo"' = "crate::types::Foo"
|
||||
/// # **NOT** `"Foo"` in SQLx (parses as just `Foo`)
|
||||
/// "Foo" = "crate::types::Foo"
|
||||
///
|
||||
/// # Schema-qualified
|
||||
/// '"foo".foo' = "crate::types::Foo"
|
||||
/// 'foo."Foo"' = "crate::types::Foo"
|
||||
/// '"foo"."Foo"' = "crate::types::Foo"
|
||||
/// ```
|
||||
///
|
||||
/// (See `Note` section above for details.)
|
||||
// TODO: allow specifying different types for input vs output
|
||||
// e.g. to accept `&[T]` on input but output `Vec<T>`
|
||||
pub type_overrides: BTreeMap<SqlType, RustType>,
|
||||
|
||||
/// Specify per-table and per-column overrides for mapping SQL types to Rust types.
|
||||
///
|
||||
/// Default type mappings are defined by the database driver.
|
||||
/// Refer to the `sqlx::types` module for details.
|
||||
///
|
||||
/// The supported syntax is similar to [`type_overrides`][Self::type_overrides],
|
||||
/// (with the same caveat for quoted names!) but column names must be qualified
|
||||
/// by a separately quoted table name, which may optionally be schema-qualified.
|
||||
///
|
||||
/// Multiple columns for the same SQL table may be written in the same table in TOML
|
||||
/// (see examples below).
|
||||
///
|
||||
/// ## Note: Orthogonal to Nullability
|
||||
/// These overrides do not affect whether `query!()` decides to wrap a column in `Option<_>`
|
||||
/// or not. They only override the inner type used.
|
||||
///
|
||||
/// ## Note: Schema Qualification
|
||||
/// Table names may be schema-qualified. If so, the schema should be part
|
||||
/// of the table name string, e.g. `'foo.bar'` to reference table `bar` in schema `foo`.
|
||||
///
|
||||
/// The schema and/or type name may additionally be quoted in the string
|
||||
/// for a quoted identifier (see next section).
|
||||
///
|
||||
/// Postgres users: schema qualification should not be used for tables in the search path.
|
||||
///
|
||||
/// ## Note: Quoted Identifiers
|
||||
/// Schema, table, or column names using quoted identifiers ([MySQL], [Postgres], [SQLite])
|
||||
/// in SQL must also be specified with quotes here.
|
||||
///
|
||||
/// Postgres and SQLite use double-quotes (`"Foo"`) while MySQL uses backticks (`\`Foo\`).
|
||||
///
|
||||
/// Note, however, that the TOML format parses way the outer pair of quotes,
|
||||
/// so for quoted names in Postgres, double-quoting is necessary,
|
||||
/// e.g. `'"Foo"'` for SQL name `"Foo"`.
|
||||
///
|
||||
/// To reference a schema-qualified table with a quoted name, use the appropriate quotation
|
||||
/// characters after the dot, e.g. `'foo."Bar"'` to reference table `"Bar"` of schema `foo`,
|
||||
/// and vice versa for quoted schema names.
|
||||
///
|
||||
/// We recommend wrapping all table and column names in single quotes, as shown below,
|
||||
/// to avoid confusion.
|
||||
///
|
||||
/// [MySQL]: https://dev.mysql.com/doc/refman/8.4/en/identifiers.html
|
||||
/// [Postgres]: https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS
|
||||
/// [SQLite]: https://sqlite.org/lang_keywords.html
|
||||
// Note: we wanted to be able to handle this intelligently,
|
||||
// but the `toml` crate authors weren't interested: https://github.com/toml-rs/toml/issues/761
|
||||
//
|
||||
// We decided to just encourage always quoting type names instead.
|
||||
///
|
||||
/// Example
|
||||
/// -------
|
||||
///
|
||||
/// #### `sqlx.toml`
|
||||
/// ```toml
|
||||
/// [macros.table-overrides.'foo']
|
||||
/// # Map column `bar` of table `foo` to Rust type `crate::types::Foo`:
|
||||
/// 'bar' = "crate::types::Bar"
|
||||
///
|
||||
/// # Quoted column name
|
||||
/// # Note: same quoting requirements as `macros.type_overrides`
|
||||
/// '"Bar"' = "crate::types::Bar"
|
||||
///
|
||||
/// # Note: will NOT work (parses as `Bar`)
|
||||
/// # "Bar" = "crate::types::Bar"
|
||||
///
|
||||
/// # Table name may be quoted (note the wrapping single-quotes)
|
||||
/// [macros.table-overrides.'"Foo"']
|
||||
/// 'bar' = "crate::types::Bar"
|
||||
/// '"Bar"' = "crate::types::Bar"
|
||||
///
|
||||
/// # Table name may also be schema-qualified.
|
||||
/// # Note how the dot is inside the quotes.
|
||||
/// [macros.table-overrides.'my_schema.my_table']
|
||||
/// 'my_column' = "crate::types::MyType"
|
||||
///
|
||||
/// # Quoted schema, table, and column names
|
||||
/// [macros.table-overrides.'"My Schema"."My Table"']
|
||||
/// '"My Column"' = "crate::types::MyType"
|
||||
/// ```
|
||||
pub table_overrides: BTreeMap<TableName, BTreeMap<ColumnName, RustType>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
#[cfg_attr(
|
||||
feature = "sqlx-toml",
|
||||
derive(serde::Deserialize),
|
||||
serde(default, rename_all = "kebab-case")
|
||||
)]
|
||||
pub struct PreferredCrates {
|
||||
/// Specify the crate to use for mapping date/time types to Rust.
|
||||
///
|
||||
/// The default behavior is to use whatever crate is enabled,
|
||||
/// [`chrono`] or [`time`] (the latter takes precedent).
|
||||
///
|
||||
/// [`chrono`]: crate::types::chrono
|
||||
/// [`time`]: crate::types::time
|
||||
///
|
||||
/// Example: Always Use Chrono
|
||||
/// -------
|
||||
/// Thanks to Cargo's [feature unification], a crate in the dependency graph may enable
|
||||
/// the `time` feature of SQLx which will force it on for all crates using SQLx,
|
||||
/// which will result in problems if your crate wants to use types from [`chrono`].
|
||||
///
|
||||
/// You can use the type override syntax (see `sqlx::query!` for details),
|
||||
/// or you can force an override globally by setting this option.
|
||||
///
|
||||
/// #### `sqlx.toml`
|
||||
/// ```toml
|
||||
/// [macros.preferred-crates]
|
||||
/// date-time = "chrono"
|
||||
/// ```
|
||||
///
|
||||
/// [feature unification]: https://doc.rust-lang.org/cargo/reference/features.html#feature-unification
|
||||
pub date_time: DateTimeCrate,
|
||||
|
||||
/// Specify the crate to use for mapping `NUMERIC` types to Rust.
|
||||
///
|
||||
/// The default behavior is to use whatever crate is enabled,
|
||||
/// [`bigdecimal`] or [`rust_decimal`] (the latter takes precedent).
|
||||
///
|
||||
/// [`bigdecimal`]: crate::types::bigdecimal
|
||||
/// [`rust_decimal`]: crate::types::rust_decimal
|
||||
///
|
||||
/// Example: Always Use `bigdecimal`
|
||||
/// -------
|
||||
/// Thanks to Cargo's [feature unification], a crate in the dependency graph may enable
|
||||
/// the `rust_decimal` feature of SQLx which will force it on for all crates using SQLx,
|
||||
/// which will result in problems if your crate wants to use types from [`bigdecimal`].
|
||||
///
|
||||
/// You can use the type override syntax (see `sqlx::query!` for details),
|
||||
/// or you can force an override globally by setting this option.
|
||||
///
|
||||
/// #### `sqlx.toml`
|
||||
/// ```toml
|
||||
/// [macros.preferred-crates]
|
||||
/// numeric = "bigdecimal"
|
||||
/// ```
|
||||
///
|
||||
/// [feature unification]: https://doc.rust-lang.org/cargo/reference/features.html#feature-unification
|
||||
pub numeric: NumericCrate,
|
||||
}
|
||||
|
||||
/// The preferred crate to use for mapping date/time types to Rust.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
#[cfg_attr(
|
||||
feature = "sqlx-toml",
|
||||
derive(serde::Deserialize),
|
||||
serde(rename_all = "snake_case")
|
||||
)]
|
||||
pub enum DateTimeCrate {
|
||||
/// Use whichever crate is enabled (`time` then `chrono`).
|
||||
#[default]
|
||||
Inferred,
|
||||
|
||||
/// Always use types from [`chrono`][crate::types::chrono].
|
||||
///
|
||||
/// ```toml
|
||||
/// [macros.preferred-crates]
|
||||
/// date-time = "chrono"
|
||||
/// ```
|
||||
Chrono,
|
||||
|
||||
/// Always use types from [`time`][crate::types::time].
|
||||
///
|
||||
/// ```toml
|
||||
/// [macros.preferred-crates]
|
||||
/// date-time = "time"
|
||||
/// ```
|
||||
Time,
|
||||
}
|
||||
|
||||
/// The preferred crate to use for mapping `NUMERIC` types to Rust.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
#[cfg_attr(
|
||||
feature = "sqlx-toml",
|
||||
derive(serde::Deserialize),
|
||||
serde(rename_all = "snake_case")
|
||||
)]
|
||||
pub enum NumericCrate {
|
||||
/// Use whichever crate is enabled (`rust_decimal` then `bigdecimal`).
|
||||
#[default]
|
||||
Inferred,
|
||||
|
||||
/// Always use types from [`bigdecimal`][crate::types::bigdecimal].
|
||||
///
|
||||
/// ```toml
|
||||
/// [macros.preferred-crates]
|
||||
/// numeric = "bigdecimal"
|
||||
/// ```
|
||||
#[cfg_attr(feature = "sqlx-toml", serde(rename = "bigdecimal"))]
|
||||
BigDecimal,
|
||||
|
||||
/// Always use types from [`rust_decimal`][crate::types::rust_decimal].
|
||||
///
|
||||
/// ```toml
|
||||
/// [macros.preferred-crates]
|
||||
/// numeric = "rust_decimal"
|
||||
/// ```
|
||||
RustDecimal,
|
||||
}
|
||||
|
||||
/// A SQL type name; may optionally be schema-qualified.
|
||||
///
|
||||
/// See [`macros.type-overrides`][Config::type_overrides] for usages.
|
||||
pub type SqlType = Box<str>;
|
||||
|
||||
/// A SQL table name; may optionally be schema-qualified.
|
||||
///
|
||||
/// See [`macros.table-overrides`][Config::table_overrides] for usages.
|
||||
pub type TableName = Box<str>;
|
||||
|
||||
/// A column in a SQL table.
|
||||
///
|
||||
/// See [`macros.table-overrides`][Config::table_overrides] for usages.
|
||||
pub type ColumnName = Box<str>;
|
||||
|
||||
/// A Rust type name or path.
|
||||
///
|
||||
/// Should be a global path (not relative).
|
||||
pub type RustType = Box<str>;
|
||||
|
||||
/// Internal getter methods.
|
||||
impl Config {
|
||||
/// Get the override for a given type name (optionally schema-qualified).
|
||||
pub fn type_override(&self, type_name: &str) -> Option<&str> {
|
||||
// TODO: make this case-insensitive
|
||||
self.type_overrides.get(type_name).map(|s| &**s)
|
||||
}
|
||||
|
||||
/// Get the override for a given column and table name (optionally schema-qualified).
|
||||
pub fn column_override(&self, table: &str, column: &str) -> Option<&str> {
|
||||
self.table_overrides
|
||||
.get(table)
|
||||
.and_then(|by_column| by_column.get(column))
|
||||
.map(|s| &**s)
|
||||
}
|
||||
}
|
||||
|
||||
impl DateTimeCrate {
|
||||
/// Returns `self == Self::Inferred`
|
||||
#[inline(always)]
|
||||
pub fn is_inferred(&self) -> bool {
|
||||
*self == Self::Inferred
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn crate_name(&self) -> Option<&str> {
|
||||
match self {
|
||||
Self::Inferred => None,
|
||||
Self::Chrono => Some("chrono"),
|
||||
Self::Time => Some("time"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl NumericCrate {
|
||||
/// Returns `self == Self::Inferred`
|
||||
#[inline(always)]
|
||||
pub fn is_inferred(&self) -> bool {
|
||||
*self == Self::Inferred
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn crate_name(&self) -> Option<&str> {
|
||||
match self {
|
||||
Self::Inferred => None,
|
||||
Self::BigDecimal => Some("bigdecimal"),
|
||||
Self::RustDecimal => Some("rust_decimal"),
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 172 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user