Compare commits

...
6 Commits
Author SHA1 Message Date
bsodfather 18e27f3994 docs(evidence): normalize sanitized diagnostic whitespace
CI / Rust Checks (pull_request) Failing after 16m45s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
2026-10-05 00:01:04 +03:00
bsodfather ce5b9af5ab docs(epic-1): record verified retrospective completion evidence 2026-10-05 00:01:04 +03:00
bsodfather c6805e2345 test(ui): preserve auto-opened onboarding panel in recovery check 2026-10-05 00:01:04 +03:00
bsodfather 45f3cabe44 fix(tooling): exclude upstream SQLx from Community marker scan 2026-10-04 23:57:40 +03:00
bsodfather 284eb8180e fix(deps): bound SQLx pool maintenance and reserve idle counters 2026-10-04 23:57:40 +03:00
bsodfather 7aa854de26 fix(epic-1): repair atomic agent edits and dispatch certainty 2026-10-04 23:57:40 +03:00
155 changed files with 25888 additions and 60 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
docs/epic-1-completion/evidence/*.patch -whitespace
+5
View File
@@ -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
View File
@@ -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",
+4
View File
@@ -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"
+9 -43
View File
@@ -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: &current.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
View File
@@ -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);
}
}
}
+1
View File
@@ -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(&registry, &operation, "mcp-certainty-agent").await;
let api_key = create_platform_api_key(
&registry,
"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}")
}
+4 -1
View File
@@ -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');
+5
View File
@@ -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
}
+101 -6
View File
@@ -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(),
}
}
+4
View File
@@ -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)
+268
View File
@@ -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 не редактировался.
+89
View File
@@ -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`.
Прерванный запуск сохраняйте отдельно от последующего успешного.
+49
View File
@@ -0,0 +1,49 @@
# 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`.
@@ -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,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
+950
View File
@@ -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."
}
}
+5
View File
@@ -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(
+11 -4
View File
@@ -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"
+71
View File
@@ -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 -1
View File
@@ -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
View File
@@ -0,0 +1,6 @@
{
"git": {
"sha1": "003b698e99e024f3621b8043a2426fde5b741171"
},
"path_in_vcs": "sqlx-core"
}
+2675
View File
File diff suppressed because it is too large. Load diff
+331
View File
@@ -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"
Generated Vendored Executable
+119
View File
@@ -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
View File
@@ -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.
Vendored Executable
+26
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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"),
}
}
}
+212
View File
@@ -0,0 +1,212 @@
use std::collections::BTreeSet;
/// Configuration for migrations when executed using `sqlx::migrate!()` or through `sqlx-cli`.
///
/// ### Note
/// A manually constructed [`Migrator`][crate::migrate::Migrator] will not be aware of these
/// configuration options. We recommend using `sqlx::migrate!()` instead.
///
/// ### Warning: Potential Data Loss or Corruption!
/// Many of these options, if changed after migrations are set up,
/// can result in data loss or corruption of a production database
/// if the proper precautions are not taken.
///
/// Be sure you know what you are doing and that you read all relevant documentation _thoroughly_.
#[derive(Debug, Default)]
#[cfg_attr(
feature = "sqlx-toml",
derive(serde::Deserialize),
serde(default, rename_all = "kebab-case", deny_unknown_fields)
)]
pub struct Config {
/// Specify the names of schemas to create if they don't already exist.
///
/// This is done before checking the existence of the migrations table
/// (`_sqlx_migrations` or overridden `table_name` below) so that it may be placed in
/// one of these schemas.
///
/// ### Example
/// `sqlx.toml`:
/// ```toml
/// [migrate]
/// create-schemas = ["foo"]
/// ```
pub create_schemas: BTreeSet<Box<str>>,
/// Override the name of the table used to track executed migrations.
///
/// May be schema-qualified and/or contain quotes. Defaults to `_sqlx_migrations`.
///
/// Potentially useful for multi-tenant databases.
///
/// ### Warning: Potential Data Loss or Corruption!
/// Changing this option for a production database will likely result in data loss or corruption
/// as the migration machinery will no longer be aware of what migrations have been applied
/// and will attempt to re-run them.
///
/// You should create the new table as a copy of the existing migrations table (with contents!),
/// and be sure all instances of your application have been migrated to the new
/// table before deleting the old one.
///
/// ### Example
/// `sqlx.toml`:
/// ```toml
/// [migrate]
/// # Put `_sqlx_migrations` in schema `foo`
/// table-name = "foo._sqlx_migrations"
/// ```
pub table_name: Option<Box<str>>,
/// Override the directory used for migrations files.
///
/// Relative to the crate root for `sqlx::migrate!()`, or the current directory for `sqlx-cli`.
pub migrations_dir: Option<Box<str>>,
/// Specify characters that should be ignored when hashing migrations.
///
/// Any characters contained in the given array will be dropped when a migration is hashed.
///
/// ### Warning: May Change Hashes for Existing Migrations
/// Changing the characters considered in hashing migrations will likely
/// change the output of the hash.
///
/// This may require manual rectification for deployed databases.
///
/// ### Example: Ignore Carriage Return (`<CR>` | `\r`)
/// Line ending differences between platforms can result in migrations having non-repeatable
/// hashes. The most common culprit is the carriage return (`<CR>` | `\r`), which Windows
/// uses in its line endings alongside line feed (`<LF>` | `\n`), often written `CRLF` or `\r\n`,
/// whereas Linux and macOS use only line feeds.
///
/// `sqlx.toml`:
/// ```toml
/// [migrate]
/// ignored-chars = ["\r"]
/// ```
///
/// For projects using Git, this can also be addressed using [`.gitattributes`]:
///
/// ```text
/// # Force newlines in migrations to be line feeds on all platforms
/// migrations/*.sql text eol=lf
/// ```
///
/// This may require resetting or re-checking out the migrations files to take effect.
///
/// [`.gitattributes`]: https://git-scm.com/docs/gitattributes
///
/// ### Example: Ignore all Whitespace Characters
/// To make your migrations amenable to reformatting, you may wish to tell SQLx to ignore
/// _all_ whitespace characters in migrations.
///
/// ##### Warning: Beware Syntactically Significant Whitespace!
/// If your migrations use string literals or quoted identifiers which contain whitespace,
/// this configuration will cause the migration machinery to ignore some changes to these.
/// This may result in a mismatch between the development and production versions of
/// your database.
///
/// `sqlx.toml`:
/// ```toml
/// [migrate]
/// # Ignore common whitespace characters when hashing
/// ignored-chars = [" ", "\t", "\r", "\n"] # Space, tab, CR, LF
/// ```
// Likely lower overhead for small sets than `HashSet`.
pub ignored_chars: BTreeSet<char>,
/// Specify default options for new migrations created with `sqlx migrate add`.
pub defaults: MigrationDefaults,
}
#[derive(Debug, Default)]
#[cfg_attr(
feature = "sqlx-toml",
derive(serde::Deserialize),
serde(default, rename_all = "kebab-case")
)]
pub struct MigrationDefaults {
/// Specify the default type of migration that `sqlx migrate add` should create by default.
///
/// ### Example: Use Reversible Migrations by Default
/// `sqlx.toml`:
/// ```toml
/// [migrate.defaults]
/// migration-type = "reversible"
/// ```
pub migration_type: DefaultMigrationType,
/// Specify the default scheme that `sqlx migrate add` should use for version integers.
///
/// ### Example: Use Sequential Versioning by Default
/// `sqlx.toml`:
/// ```toml
/// [migrate.defaults]
/// migration-versioning = "sequential"
/// ```
pub migration_versioning: DefaultVersioning,
}
/// The default type of migration that `sqlx migrate add` should create by default.
#[derive(Debug, Default, PartialEq, Eq)]
#[cfg_attr(
feature = "sqlx-toml",
derive(serde::Deserialize),
serde(rename_all = "snake_case")
)]
pub enum DefaultMigrationType {
/// Create the same migration type as that of the latest existing migration,
/// or `Simple` otherwise.
#[default]
Inferred,
/// Create non-reversible migrations (`<VERSION>_<DESCRIPTION>.sql`) by default.
Simple,
/// Create reversible migrations (`<VERSION>_<DESCRIPTION>.up.sql` and `[...].down.sql`) by default.
Reversible,
}
/// The default scheme that `sqlx migrate add` should use for version integers.
#[derive(Debug, Default, PartialEq, Eq)]
#[cfg_attr(
feature = "sqlx-toml",
derive(serde::Deserialize),
serde(rename_all = "snake_case")
)]
pub enum DefaultVersioning {
/// Infer the versioning scheme from existing migrations:
///
/// * If the versions of the last two migrations differ by `1`, infer `Sequential`.
/// * If only one migration exists and has version `1`, infer `Sequential`.
/// * Otherwise, infer `Timestamp`.
#[default]
Inferred,
/// Use UTC timestamps for migration versions.
///
/// This is the recommended versioning format as it's less likely to collide when multiple
/// developers are creating migrations on different branches.
///
/// The exact timestamp format is unspecified.
Timestamp,
/// Use sequential integers for migration versions.
Sequential,
}
#[cfg(feature = "migrate")]
impl Config {
pub fn migrations_dir(&self) -> &str {
self.migrations_dir.as_deref().unwrap_or("migrations")
}
pub fn table_name(&self) -> &str {
self.table_name.as_deref().unwrap_or("_sqlx_migrations")
}
pub fn to_resolve_config(&self) -> crate::migrate::ResolveConfig {
let mut config = crate::migrate::ResolveConfig::new();
config.ignore_chars(self.ignored_chars.iter().copied());
config
}
}
+223
View File
@@ -0,0 +1,223 @@
//! (Exported for documentation only) Guide and reference for `sqlx.toml` files.
//!
//! To use, create a `sqlx.toml` file in your crate root (the same directory as your `Cargo.toml`).
//! The configuration in a `sqlx.toml` configures SQLx *only* for the current crate.
//!
//! Requires the `sqlx-toml` feature (not enabled by default).
//!
//! `sqlx-cli` will also read `sqlx.toml` when running migrations.
//!
//! See the [`Config`] type and its fields for individual configuration options.
//!
//! See the [reference][`_reference`] for the full `sqlx.toml` file.
use std::error::Error;
use std::fmt::Debug;
use std::io;
use std::path::{Path, PathBuf};
/// Configuration shared by multiple components.
///
/// See [`common::Config`] for details.
pub mod common;
pub mod drivers;
/// Configuration for the `query!()` family of macros.
///
/// See [`macros::Config`] for details.
pub mod macros;
/// Configuration for migrations when executed using `sqlx::migrate!()` or through `sqlx-cli`.
///
/// See [`migrate::Config`] for details.
pub mod migrate;
/// Reference for `sqlx.toml` files
///
/// Source: `sqlx-core/src/config/reference.toml`
///
/// ```toml
#[doc = include_str!("reference.toml")]
/// ```
pub mod _reference {}
#[cfg(all(test, feature = "sqlx-toml"))]
mod tests;
/// The parsed structure of a `sqlx.toml` file.
#[derive(Debug, Default)]
#[cfg_attr(
feature = "sqlx-toml",
derive(serde::Deserialize),
serde(default, rename_all = "kebab-case", deny_unknown_fields)
)]
pub struct Config {
/// Configuration shared by multiple components.
///
/// See [`common::Config`] for details.
pub common: common::Config,
/// Configuration for database drivers.
///
/// See [`drivers::Config`] for details.
pub drivers: drivers::Config,
/// Configuration for the `query!()` family of macros.
///
/// See [`macros::Config`] for details.
pub macros: macros::Config,
/// Configuration for migrations when executed using `sqlx::migrate!()` or through `sqlx-cli`.
///
/// See [`migrate::Config`] for details.
pub migrate: migrate::Config,
}
/// Error returned from various methods of [`Config`].
#[derive(thiserror::Error, Debug)]
pub enum ConfigError {
/// The loading method expected `CARGO_MANIFEST_DIR` to be set and it wasn't.
///
/// This is necessary to locate the root of the crate currently being compiled.
///
/// See [the "Environment Variables" page of the Cargo Book][cargo-env] for details.
///
/// [cargo-env]: https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates
#[error("environment variable `CARGO_MANIFEST_DIR` must be set and valid")]
Env(
#[from]
#[source]
std::env::VarError,
),
/// No configuration file was found. Not necessarily fatal.
#[error("config file {path:?} not found")]
NotFound { path: PathBuf },
/// An I/O error occurred while attempting to read the config file at `path`.
///
/// If the error is [`io::ErrorKind::NotFound`], [`Self::NotFound`] is returned instead.
#[error("error reading config file {path:?}")]
Io {
path: PathBuf,
#[source]
error: io::Error,
},
/// An error in the TOML was encountered while parsing the config file at `path`.
///
/// The error gives line numbers and context when printed with `Display`/`ToString`.
///
/// Only returned if the `sqlx-toml` feature is enabled.
#[error("error parsing config file {path:?}")]
Parse {
path: PathBuf,
/// Type-erased [`toml::de::Error`].
#[source]
error: Box<dyn Error + Send + Sync + 'static>,
},
/// A `sqlx.toml` file was found or specified, but the `sqlx-toml` feature is not enabled.
#[error("SQLx found config file at {path:?} but the `sqlx-toml` feature was not enabled")]
ParseDisabled { path: PathBuf },
}
impl ConfigError {
/// Create a [`ConfigError`] from a [`std::io::Error`].
///
/// Maps to either `NotFound` or `Io`.
pub fn from_io(path: impl Into<PathBuf>, error: io::Error) -> Self {
if error.kind() == io::ErrorKind::NotFound {
Self::NotFound { path: path.into() }
} else {
Self::Io {
path: path.into(),
error,
}
}
}
/// If this error means the file was not found, return the path that was attempted.
pub fn not_found_path(&self) -> Option<&Path> {
if let Self::NotFound { path } = self {
Some(path)
} else {
None
}
}
}
/// Internal methods for loading a `Config`.
#[allow(clippy::result_large_err)]
impl Config {
/// Read `$CARGO_MANIFEST_DIR/sqlx.toml` or return `Config::default()` if it does not exist.
///
/// # Errors
/// * If `CARGO_MANIFEST_DIR` is not set.
/// * If the file exists but could not be read or parsed.
/// * If the file exists but the `sqlx-toml` feature is disabled.
pub fn try_from_crate_or_default() -> Result<Self, ConfigError> {
Self::try_from_path_or_default(get_crate_path()?)
}
/// Attempt to read `Config` from the path given, or return `Config::default()` if it does not exist.
///
/// # Errors
/// * If the file exists but could not be read or parsed.
/// * If the file exists but the `sqlx-toml` feature is disabled.
pub fn try_from_path_or_default(path: PathBuf) -> Result<Self, ConfigError> {
Self::read_from(path).or_else(|e| {
if let ConfigError::NotFound { .. } = e {
Ok(Config::default())
} else {
Err(e)
}
})
}
/// Attempt to read `Config` from the path given.
///
/// # Errors
/// * If the file does not exist.
/// * If the file exists but could not be read or parsed.
/// * If the file exists but the `sqlx-toml` feature is disabled.
pub fn try_from_path(path: PathBuf) -> Result<Self, ConfigError> {
Self::read_from(path)
}
#[cfg(feature = "sqlx-toml")]
fn read_from(path: PathBuf) -> Result<Self, ConfigError> {
// The `toml` crate doesn't provide an incremental reader.
let toml_s = match std::fs::read_to_string(&path) {
Ok(toml) => toml,
Err(error) => {
return Err(ConfigError::from_io(path, error));
}
};
// TODO: parse and lint TOML structure before deserializing
// Motivation: https://github.com/toml-rs/toml/issues/761
tracing::debug!("read config TOML from {path:?}:\n{toml_s}");
toml::from_str(&toml_s).map_err(|error| ConfigError::Parse {
path,
error: Box::new(error),
})
}
#[cfg(not(feature = "sqlx-toml"))]
fn read_from(path: PathBuf) -> Result<Self, ConfigError> {
match path.try_exists() {
Ok(true) => Err(ConfigError::ParseDisabled { path }),
Ok(false) => Err(ConfigError::NotFound { path }),
Err(e) => Err(ConfigError::from_io(path, e)),
}
}
}
fn get_crate_path() -> Result<PathBuf, ConfigError> {
let mut path = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR")?);
path.push("sqlx.toml");
Ok(path)
}
+236
View File
@@ -0,0 +1,236 @@
# `sqlx.toml` reference.
#
# Note: shown values are *not* defaults.
# They are explicitly set to non-default values to test parsing.
# Refer to the comment for a given option for its default value.
###############################################################################################
# Configuration shared by multiple components.
[common]
# Change the environment variable to get the database URL.
#
# This is used by both the macros and `sqlx-cli`.
#
# If not specified, defaults to `DATABASE_URL`
database-url-var = "FOO_DATABASE_URL"
###############################################################################################
# Configuration of SQLx database drivers (**applies to macros and sqlx-cli only**)
[drivers]
# Configure MySQL databases in macros and sqlx-cli.
[drivers.mysql]
# No fields implemented yet. This key is only used to validate parsing.
# Configure Postgres databases in macros and sqlx-cli.
[drivers.postgres]
# No fields implemented yet. This key is only used to validate parsing.
# Configure Postgres databases in macros and sqlx-cli.
[drivers.sqlite]
# Load extensions into SQLite when running macros or migrations
#
# Defaults to an empty list, which has no effect.
#
# Must be specified separately at run-time using `SqliteConnectOptions::extension()` or `::extension_with_entrypoint()`.
#
# Safety
# This causes arbitrary DLLs on the filesystem to be loaded at runtime,
# 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.
unsafe-load-extensions = [
"uuid",
{ path = "vsv_renamed", entrypoint = "sqlite3_vsv_init" },
]
# Configure external drivers in macros and sqlx-cli.
#
# These keys are only validated when the external driver tries to parse them,
# unlike config for built-in drivers which is validated directly.
[drivers.external."<external driver name>"]
foo = 'foo'
bar = true
###############################################################################################
# Configuration for the `query!()` family of macros.
[macros]
[macros.preferred-crates]
# Force the macros to use the `chrono` crate for date/time types, even if `time` is enabled.
#
# Defaults to "inferred": use whichever crate is enabled (`time` takes precedence over `chrono`).
date-time = "chrono"
# Or, ensure the macros always prefer `time`
# in case new date/time crates are added in the future:
# date-time = "time"
# Force the macros to use the `rust_decimal` crate for `NUMERIC`, even if `bigdecimal` is enabled.
#
# Defaults to "inferred": use whichever crate is enabled (`bigdecimal` takes precedence over `rust_decimal`).
numeric = "rust_decimal"
# Or, ensure the macros always prefer `bigdecimal`
# in case new decimal crates are added in the future:
# numeric = "bigdecimal"
# Set global 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.
#
# Postgres users: schema qualification should not be used for types in the search path.
#
# ### 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.
[macros.type-overrides]
# Override a built-in type (map all `UUID` columns to `crate::types::MyUuid`)
# Note: currently, the case of the type name MUST match.
# Built-in types are spelled in all-uppercase to match SQL convention.
'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::isbn::ISBN13"
# SQL type `foo` to Rust type `crate::types::Foo`:
'foo' = "crate::types::Foo"
# SQL type `"Bar"` to Rust type `crate::types::Bar`; notice the extra pair of quotes:
'"Bar"' = "crate::types::Bar"
# Will NOT work (the first pair of quotes are parsed by TOML)
# "Bar" = "crate::types::Bar"
# Schema qualified
'foo.bar' = "crate::types::Bar"
# Schema qualified and quoted
'foo."Bar"' = "crate::schema::foo::Bar"
# Quoted schema name
'"Foo".bar' = "crate::schema::foo::Bar"
# Quoted schema and type name
'"Foo"."Bar"' = "crate::schema::foo::Bar"
# Set per-table and per-column overrides for mapping SQL types to Rust types.
#
# Note: table name is required in the header.
#
# Postgres users: schema qualification should not be used for types in the search path.
#
# ### 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.
[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"
###############################################################################################
# Configuration for migrations when executed using `sqlx::migrate!()` or through `sqlx-cli`.
#
# ### Note
# A manually constructed [`Migrator`][crate::migrate::Migrator] will not be aware of these
# configuration options. We recommend using `sqlx::migrate!()` instead.
#
# ### Warning: Potential Data Loss or Corruption!
# Many of these options, if changed after migrations are set up,
# can result in data loss or corruption of a production database
# if the proper precautions are not taken.
#
# Be sure you know what you are doing and that you read all relevant documentation _thoroughly_.
[migrate]
# Override the name of the table used to track executed migrations.
#
# May be schema-qualified and/or contain quotes. Defaults to `_sqlx_migrations`.
#
# Potentially useful for multi-tenant databases.
#
# ### Warning: Potential Data Loss or Corruption!
# Changing this option for a production database will likely result in data loss or corruption
# as the migration machinery will no longer be aware of what migrations have been applied
# and will attempt to re-run them.
#
# You should create the new table as a copy of the existing migrations table (with contents!),
# and be sure all instances of your application have been migrated to the new
# table before deleting the old one.
table-name = "foo._sqlx_migrations"
# Override the directory used for migrations files.
#
# Relative to the crate root for `sqlx::migrate!()`, or the current directory for `sqlx-cli`.
migrations-dir = "foo/migrations"
# Specify characters that should be ignored when hashing migrations.
#
# Any characters contained in the given set will be dropped when a migration is hashed.
#
# Defaults to an empty array (don't drop any characters).
#
# ### Warning: May Change Hashes for Existing Migrations
# Changing the characters considered in hashing migrations will likely
# change the output of the hash.
#
# This may require manual rectification for deployed databases.
# ignored-chars = []
# Ignore Carriage Returns (`<CR>` | `\r`)
# Note that the TOML format requires double-quoted strings to process escapes.
# ignored-chars = ["\r"]
# Ignore common whitespace characters (beware syntactically significant whitespace!)
# Space, tab, CR, LF, zero-width non-breaking space (U+FEFF)
#
# U+FEFF is added by some editors as a magic number at the beginning of a text file indicating it is UTF-8 encoded,
# where it is known as a byte-order mark (BOM): https://en.wikipedia.org/wiki/Byte_order_mark
ignored-chars = [" ", "\t", "\r", "\n", "\uFEFF"]
# Set default options for new migrations.
[migrate.defaults]
# Specify reversible migrations by default (for `sqlx migrate create`).
#
# Defaults to "inferred": uses the type of the last migration, or "simple" otherwise.
migration-type = "reversible"
# Specify simple (non-reversible) migrations by default.
# migration-type = "simple"
# Specify sequential versioning by default (for `sqlx migrate create`).
#
# Defaults to "inferred": guesses the versioning scheme from the latest migrations,
# or "timestamp" otherwise.
migration-versioning = "sequential"
# Specify timestamp versioning by default.
# migration-versioning = "timestamp"
+122
View File
@@ -0,0 +1,122 @@
use crate::config::{self, Config};
use std::collections::BTreeSet;
#[test]
fn reference_parses_as_config() {
let config: Config = toml::from_str(include_str!("reference.toml"))
// The `Display` impl of `toml::Error` is *actually* more useful than `Debug`
.unwrap_or_else(|e| panic!("expected reference.toml to parse as Config: {e}"));
assert_common_config(&config.common);
assert_drivers_config(&config.drivers);
assert_macros_config(&config.macros);
assert_migrate_config(&config.migrate);
}
fn assert_common_config(config: &config::common::Config) {
assert_eq!(config.database_url_var.as_deref(), Some("FOO_DATABASE_URL"));
}
fn assert_drivers_config(config: &config::drivers::Config) {
assert_eq!(
config.sqlite.unsafe_load_extensions,
vec![
config::drivers::SqliteExtension::Path("uuid".to_string()),
config::drivers::SqliteExtension::PathWithEntrypoint {
path: "vsv_renamed".to_string(),
entrypoint: "sqlite3_vsv_init".to_string()
}
]
);
#[derive(Debug, Eq, PartialEq, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
struct TestExternalDriverConfig {
foo: String,
bar: bool,
}
assert_eq!(
config.external.try_parse("<external driver name>").unwrap(),
Some(TestExternalDriverConfig {
foo: "foo".to_string(),
bar: true
})
);
}
fn assert_macros_config(config: &config::macros::Config) {
use config::macros::*;
assert_eq!(config.preferred_crates.date_time, DateTimeCrate::Chrono);
assert_eq!(config.preferred_crates.numeric, NumericCrate::RustDecimal);
// Type overrides
// Don't need to cover everything, just some important canaries.
assert_eq!(config.type_override("UUID"), Some("crate::types::MyUuid"));
assert_eq!(config.type_override("foo"), Some("crate::types::Foo"));
assert_eq!(config.type_override(r#""Bar""#), Some("crate::types::Bar"),);
assert_eq!(
config.type_override(r#""Foo".bar"#),
Some("crate::schema::foo::Bar"),
);
assert_eq!(
config.type_override(r#""Foo"."Bar""#),
Some("crate::schema::foo::Bar"),
);
// Column overrides
assert_eq!(
config.column_override("foo", "bar"),
Some("crate::types::Bar"),
);
assert_eq!(
config.column_override("foo", r#""Bar""#),
Some("crate::types::Bar"),
);
assert_eq!(
config.column_override(r#""Foo""#, "bar"),
Some("crate::types::Bar"),
);
assert_eq!(
config.column_override(r#""Foo""#, r#""Bar""#),
Some("crate::types::Bar"),
);
assert_eq!(
config.column_override("my_schema.my_table", "my_column"),
Some("crate::types::MyType"),
);
assert_eq!(
config.column_override(r#""My Schema"."My Table""#, r#""My Column""#),
Some("crate::types::MyType"),
);
}
fn assert_migrate_config(config: &config::migrate::Config) {
use config::migrate::*;
assert_eq!(config.table_name.as_deref(), Some("foo._sqlx_migrations"));
assert_eq!(config.migrations_dir.as_deref(), Some("foo/migrations"));
let ignored_chars = BTreeSet::from([' ', '\t', '\r', '\n', '\u{FEFF}']);
assert_eq!(config.ignored_chars, ignored_chars);
assert_eq!(
config.defaults.migration_type,
DefaultMigrationType::Reversible
);
assert_eq!(
config.defaults.migration_versioning,
DefaultVersioning::Sequential
);
}
+281
View File
@@ -0,0 +1,281 @@
use crate::database::{Database, HasStatementCache};
use crate::error::Error;
use crate::config;
use crate::sql_str::SqlSafeStr;
use crate::transaction::{Transaction, TransactionManager};
use futures_core::future::BoxFuture;
use log::LevelFilter;
use std::fmt::Debug;
use std::future::Future;
use std::str::FromStr;
use std::time::Duration;
use url::Url;
/// Represents a single database connection.
pub trait Connection: Send {
type Database: Database<Connection = Self>;
type Options: ConnectOptions<Connection = Self>;
/// Explicitly close this database connection.
///
/// This notifies the database server that the connection is closing so that it can
/// free up any server-side resources in use.
///
/// While connections can simply be dropped to clean up local resources,
/// the `Drop` handler itself cannot notify the server that the connection is being closed
/// because that may require I/O to send a termination message. That can result in a delay
/// before the server learns that the connection is gone, usually from a TCP keepalive timeout.
///
/// Creating and dropping many connections in short order without calling `.close()` may
/// lead to errors from the database server because those senescent connections will still
/// count against any connection limit or quota that is configured.
///
/// Therefore it is recommended to call `.close()` on a connection when you are done using it
/// and to `.await` the result to ensure the termination message is sent.
fn close(self) -> impl Future<Output = Result<(), Error>> + Send + 'static;
/// 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) -> impl Future<Output = Result<(), Error>> + Send + 'static;
/// Checks if a connection to the database is still valid.
fn ping(&mut self) -> impl Future<Output = Result<(), Error>> + Send + '_;
/// Begin a new transaction or establish a savepoint within the active transaction.
///
/// Returns a [`Transaction`] for controlling and tracking the new transaction.
fn begin(
&mut self,
) -> impl Future<Output = Result<Transaction<'_, Self::Database>, Error>> + Send + '_;
/// Begin a new transaction with a custom statement.
///
/// Returns a [`Transaction`] for controlling and tracking the new transaction.
///
/// Returns an error if the connection is already in a transaction or if
/// `statement` does not put the connection into a transaction.
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()))
}
/// Returns `true` if the connection is currently in a transaction.
///
/// # Note: Automatic Rollbacks May Not Be Counted
/// Certain database errors (such as a serializable isolation failure)
/// can cause automatic rollbacks of a transaction
/// which may not be indicated in the return value of this method.
#[inline]
fn is_in_transaction(&self) -> bool {
<Self::Database as Database>::TransactionManager::get_transaction_depth(self) != 0
}
/// Execute the function inside a transaction.
///
/// If the function returns an error, the transaction will be rolled back. If it does not
/// return an error, the transaction will be committed.
///
/// # Example
///
/// ```rust
/// use sqlx::postgres::{PgConnection, PgRow};
/// use sqlx::Connection;
///
/// # pub async fn _f(conn: &mut PgConnection) -> sqlx::Result<Vec<PgRow>> {
/// conn.transaction(|txn| Box::pin(async move {
/// sqlx::query("select * from ..").fetch_all(&mut **txn).await
/// })).await
/// # }
/// ```
fn transaction<'a, F, R, E>(
&'a mut self,
callback: F,
) -> impl Future<Output = Result<R, E>> + Send + 'a
where
for<'c> F: FnOnce(&'c mut Transaction<'_, Self::Database>) -> BoxFuture<'c, Result<R, E>>
+ 'a
+ Send
+ Sync,
Self: Sized,
R: Send,
E: From<Error> + Send,
{
async move {
let mut transaction = self.begin().await?;
let ret = callback(&mut transaction).await;
match ret {
Ok(ret) => {
transaction.commit().await?;
Ok(ret)
}
Err(err) => {
transaction.rollback().await?;
Err(err)
}
}
}
}
/// The number of statements currently cached in the connection.
fn cached_statements_size(&self) -> usize
where
Self::Database: HasStatementCache,
{
0
}
/// Removes all statements from the cache, closing them on the server if
/// needed.
fn clear_cached_statements(&mut self) -> impl Future<Output = Result<(), Error>> + Send + '_
where
Self::Database: HasStatementCache,
{
async move { Ok(()) }
}
/// Restore any buffers in the connection to their default capacity, if possible.
///
/// Sending a large query or receiving a resultset with many columns can cause the connection
/// to allocate additional buffer space to fit the data which is retained afterwards in
/// case it's needed again. This can give the outward appearance of a memory leak, but is
/// in fact the intended behavior.
///
/// Calling this method tells the connection to release that excess memory if it can,
/// though be aware that calling this too often can cause unnecessary thrashing or
/// fragmentation in the global allocator. If there's still data in the connection buffers
/// (unlikely if the last query was run to completion) then it may need to be moved to
/// allow the buffers to shrink.
fn shrink_buffers(&mut self);
#[doc(hidden)]
fn flush(&mut self) -> impl Future<Output = Result<(), Error>> + Send + '_;
#[doc(hidden)]
fn should_flush(&self) -> bool;
/// Establish a new database connection.
///
/// A value of [`Options`][Self::Options] is parsed from the provided connection string. This parsing
/// is database-specific.
#[inline]
fn connect(url: &str) -> impl Future<Output = Result<Self, Error>> + Send + 'static
where
Self: Sized,
{
let options = url.parse();
async move { Self::connect_with(&options?).await }
}
/// Establish a new database connection with the provided options.
fn connect_with(
options: &Self::Options,
) -> impl Future<Output = Result<Self, Error>> + Send + '_
where
Self: Sized,
{
options.connect()
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct LogSettings {
pub statements_level: LevelFilter,
pub slow_statements_level: LevelFilter,
pub slow_statements_duration: Duration,
}
impl Default for LogSettings {
fn default() -> Self {
LogSettings {
statements_level: LevelFilter::Debug,
slow_statements_level: LevelFilter::Warn,
slow_statements_duration: Duration::from_secs(1),
}
}
}
impl LogSettings {
pub fn log_statements(&mut self, level: LevelFilter) {
self.statements_level = level;
}
pub fn log_slow_statements(&mut self, level: LevelFilter, duration: Duration) {
self.slow_statements_level = level;
self.slow_statements_duration = duration;
}
}
pub trait ConnectOptions: 'static + Send + Sync + FromStr<Err = Error> + Debug + Clone {
type Connection: Connection<Options = Self> + ?Sized;
/// Parse the `ConnectOptions` from a URL.
fn from_url(url: &Url) -> Result<Self, Error>;
/// Get a connection URL that may be used to connect to the same database as this `ConnectOptions`.
///
/// ### Note: Lossy
/// Any flags or settings which do not have a representation in the URL format will be lost.
/// They will fall back to their default settings when the URL is parsed.
///
/// The only settings guaranteed to be preserved are:
/// * Username
/// * Password
/// * Hostname
/// * Port
/// * Database name
/// * Unix socket or SQLite database file path
/// * SSL mode (if applicable)
/// * SSL CA certificate path
/// * SSL client certificate path
/// * SSL client key path
///
/// Additional settings are driver-specific. Refer to the source of a given implementation
/// to see which options are preserved in the URL.
///
/// ### Panics
/// This defaults to `unimplemented!()`.
///
/// Individual drivers should override this to implement the intended behavior.
fn to_url_lossy(&self) -> Url {
unimplemented!()
}
/// Establish a new database connection with the options specified by `self`.
fn connect(&self) -> impl Future<Output = Result<Self::Connection, Error>> + Send + '_
where
Self::Connection: Sized;
/// Log executed statements with the specified `level`
fn log_statements(self, level: LevelFilter) -> Self;
/// Log executed statements with a duration above the specified `duration`
/// at the specified `level`.
fn log_slow_statements(self, level: LevelFilter, duration: Duration) -> Self;
/// Entirely disables statement logging (both slow and regular).
fn disable_statement_logging(self) -> Self {
self.log_statements(LevelFilter::Off)
.log_slow_statements(LevelFilter::Off, Duration::default())
}
#[doc(hidden)]
fn __unstable_apply_driver_config(
self,
_config: &config::drivers::Config,
) -> crate::Result<Self> {
Ok(self)
}
}
+114
View File
@@ -0,0 +1,114 @@
//! Traits to represent a database driver.
//!
//! # Support
//!
//! ## Tier 1
//!
//! Tier 1 support can be thought of as "guaranteed to work". Automated testing is setup to
//! ensure a high level of stability and functionality.
//!
//! | Database | Version | Driver |
//! | - | - | - |
//! | [MariaDB] | 10.1+ | [`mysql`] |
//! | [Microsoft SQL Server] | 2019 | [`mssql`] (Pending a full rewrite) |
//! | [MySQL] | 5.6, 5.7, 8.0 | [`mysql`] |
//! | [PostgreSQL] | 13+ | [`postgres`] |
//! | [SQLite] | 3.20.1+ | [`sqlite`] |
//!
//! [MariaDB]: https://mariadb.com/
//! [MySQL]: https://www.mysql.com/
//! [Microsoft SQL Server]: https://www.microsoft.com/en-us/sql-server
//! [PostgreSQL]: https://www.postgresql.org/
//! [SQLite]: https://www.sqlite.org/
//!
//! [`mysql`]: crate::mysql
//! [`postgres`]: crate::postgres
//! [`mssql`]: crate::mssql
//! [`sqlite`]: crate::sqlite
//!
//! ## Tier 2
//!
//! Tier 2 support can be thought as "should work". No specific automated testing is done,
//! at this time, but there are efforts to ensure compatibility. Tier 2 support also includes
//! database distributions that provide protocols that closely match a database from Tier 1.
//!
//! _No databases are in tier 2 at this time._
//!
//! # `Any`
//!
//! Selecting a database driver is, by default, a compile-time decision. SQLx is designed this way
//! to take full advantage of the performance and type safety made available by Rust.
//!
//! We recognize that you may wish to make a runtime decision to decide the database driver. The
//! [`Any`](crate::any) driver is provided for that purpose.
//!
//! ## Example
//!
//! ```rust,ignore
//! // connect to SQLite
//! let conn = AnyConnection::connect("sqlite://file.db").await?;
//!
//! // connect to Postgres, no code change
//! // required, decided by the scheme of the URL
//! let conn = AnyConnection::connect("postgres://localhost/sqlx").await?;
//! ```
use std::fmt::Debug;
use crate::arguments::Arguments;
use crate::column::Column;
use crate::connection::Connection;
use crate::row::Row;
use crate::statement::Statement;
use crate::transaction::TransactionManager;
use crate::type_info::TypeInfo;
use crate::value::{Value, ValueRef};
/// A database driver.
///
/// This trait encapsulates a complete set of traits that implement a driver for a
/// specific database (e.g., MySQL, PostgreSQL).
pub trait Database: 'static + Sized + Send + Debug {
/// The concrete `Connection` implementation for this database.
type Connection: Connection<Database = Self>;
/// The concrete `TransactionManager` implementation for this database.
type TransactionManager: TransactionManager<Database = Self>;
/// The concrete `Row` implementation for this database.
type Row: Row<Database = Self>;
/// The concrete `QueryResult` implementation for this database.
type QueryResult: 'static + Sized + Send + Sync + Default + Extend<Self::QueryResult>;
/// The concrete `Column` implementation for this database.
type Column: Column<Database = Self>;
/// The concrete `TypeInfo` implementation for this database.
type TypeInfo: TypeInfo;
/// The concrete type used to hold an owned copy of the not-yet-decoded value that was
/// received from the database.
type Value: Value<Database = Self> + 'static;
/// The concrete type used to hold a reference to the not-yet-decoded value that has just been
/// received from the database.
type ValueRef<'r>: ValueRef<'r, Database = Self>;
/// The concrete `Arguments` implementation for this database.
type Arguments: Arguments<Database = Self>;
/// The concrete type used as a buffer for arguments while encoding.
type ArgumentBuffer;
/// The concrete `Statement` implementation for this database.
type Statement: Statement<Database = Self>;
/// The display name for this database driver.
const NAME: &'static str;
/// The schemes for database URLs that should match this driver.
const URL_SCHEMES: &'static [&'static str];
}
/// A [`Database`] that maintains a client-side cache of prepared statements.
pub trait HasStatementCache {}
+140
View File
@@ -0,0 +1,140 @@
//! Provides [`Decode`] for decoding values from the database.
use std::borrow::Cow;
use std::rc::Rc;
use std::sync::Arc;
use crate::database::Database;
use crate::error::BoxDynError;
use crate::value::ValueRef;
/// A type that can be decoded from the database.
///
/// ## How can I implement `Decode`?
///
/// A manual implementation of `Decode` can be useful when adding support for
/// types externally to SQLx.
///
/// The following showcases how to implement `Decode` to be generic over [`Database`]. The
/// implementation can be marginally simpler if you remove the `DB` type parameter and explicitly
/// use the concrete [`ValueRef`](Database::ValueRef) and [`TypeInfo`](Database::TypeInfo) types.
///
/// ```rust
/// # use sqlx_core::database::{Database};
/// # use sqlx_core::decode::Decode;
/// # use sqlx_core::types::Type;
/// # use std::error::Error;
/// #
/// struct MyType;
///
/// # impl<DB: Database> Type<DB> for MyType {
/// # fn type_info() -> DB::TypeInfo { todo!() }
/// # }
/// #
/// # impl std::str::FromStr for MyType {
/// # type Err = sqlx_core::error::Error;
/// # fn from_str(s: &str) -> Result<Self, Self::Err> { todo!() }
/// # }
/// #
/// // DB is the database driver
/// // `'r` is the lifetime of the `Row` being decoded
/// impl<'r, DB: Database> Decode<'r, DB> for MyType
/// where
/// // we want to delegate some of the work to string decoding so let's make sure strings
/// // are supported by the database
/// &'r str: Decode<'r, DB>
/// {
/// fn decode(
/// value: <DB as Database>::ValueRef<'r>,
/// ) -> Result<MyType, Box<dyn Error + 'static + Send + Sync>> {
/// // the interface of ValueRef is largely unstable at the moment
/// // so this is not directly implementable
///
/// // however, you can delegate to a type that matches the format of the type you want
/// // to decode (such as a UTF-8 string)
///
/// let value = <&str as Decode<DB>>::decode(value)?;
///
/// // now you can parse this into your type (assuming there is a `FromStr`)
///
/// Ok(value.parse()?)
/// }
/// }
/// ```
pub trait Decode<'r, DB: Database>: Sized {
/// Decode a new value of this type using a raw value from the database.
fn decode(value: <DB as Database>::ValueRef<'r>) -> Result<Self, BoxDynError>;
}
// implement `Decode` for Option<T> for all SQL types
impl<'r, DB, T> Decode<'r, DB> for Option<T>
where
DB: Database,
T: Decode<'r, DB>,
{
fn decode(value: <DB as Database>::ValueRef<'r>) -> Result<Self, BoxDynError> {
if value.is_null() {
Ok(None)
} else {
Ok(Some(T::decode(value)?))
}
}
}
macro_rules! impl_decode_for_smartpointer {
($smart_pointer:tt) => {
impl<'r, DB, T> Decode<'r, DB> for $smart_pointer<T>
where
DB: Database,
T: Decode<'r, DB>,
{
fn decode(value: <DB as Database>::ValueRef<'r>) -> Result<Self, BoxDynError> {
Ok(Self::new(T::decode(value)?))
}
}
impl<'r, DB> Decode<'r, DB> for $smart_pointer<str>
where
DB: Database,
&'r str: Decode<'r, DB>,
{
fn decode(value: <DB as Database>::ValueRef<'r>) -> Result<Self, BoxDynError> {
let ref_str = <&str as Decode<DB>>::decode(value)?;
Ok(ref_str.into())
}
}
impl<'r, DB> Decode<'r, DB> for $smart_pointer<[u8]>
where
DB: Database,
Vec<u8>: Decode<'r, DB>,
{
fn decode(value: <DB as Database>::ValueRef<'r>) -> Result<Self, BoxDynError> {
// The `Postgres` implementation requires this to be decoded as an owned value because
// bytes can be sent in text format.
let bytes = <Vec<u8> as Decode<DB>>::decode(value)?;
Ok(bytes.into())
}
}
};
}
impl_decode_for_smartpointer!(Arc);
impl_decode_for_smartpointer!(Box);
impl_decode_for_smartpointer!(Rc);
// implement `Decode` for Cow<T> for all SQL types
impl<'r, DB, T> Decode<'r, DB> for Cow<'_, T>
where
DB: Database,
// `ToOwned` is required here to satisfy `Cow`
T: ToOwned + ?Sized,
<T as ToOwned>::Owned: Decode<'r, DB>,
{
fn decode(value: <DB as Database>::ValueRef<'r>) -> Result<Self, BoxDynError> {
// See https://github.com/launchbadge/sqlx/pull/3674#discussion_r2008611502 for more info
// about why decoding to a `Cow::Owned` was chosen.
<<T as ToOwned>::Owned as Decode<DB>>::decode(value).map(Cow::Owned)
}
}
+101
View File
@@ -0,0 +1,101 @@
use crate::database::Database;
use either::Either;
use std::convert::identity;
/// Provides extended information on a statement.
///
/// Returned from [`Executor::describe`].
///
/// The query macros (e.g., `query!`, `query_as!`, etc.) use the information here to validate
/// output and parameter types; and, generate an anonymous record.
#[derive(Debug)]
#[cfg_attr(feature = "offline", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
feature = "offline",
serde(bound(
serialize = "DB::TypeInfo: serde::Serialize, DB::Column: serde::Serialize",
deserialize = "DB::TypeInfo: serde::de::DeserializeOwned, DB::Column: serde::de::DeserializeOwned",
))
)]
#[doc(hidden)]
pub struct Describe<DB: Database> {
pub columns: Vec<DB::Column>,
pub parameters: Option<Either<Vec<DB::TypeInfo>, usize>>,
pub nullable: Vec<Option<bool>>,
}
impl<DB: Database> Describe<DB> {
/// Gets all columns in this statement.
pub fn columns(&self) -> &[DB::Column] {
&self.columns
}
/// Gets the column information at `index`.
///
/// Panics if `index` is out of bounds.
pub fn column(&self, index: usize) -> &DB::Column {
&self.columns[index]
}
/// Gets the available information for parameters in this statement.
///
/// Some drivers may return more or less than others. As an example, **PostgreSQL** will
/// return `Some(Either::Left(_))` with a full list of type information for each parameter.
/// However, **MSSQL** will return `None` as there is no information available.
pub fn parameters(&self) -> Option<Either<&[DB::TypeInfo], usize>> {
self.parameters.as_ref().map(|p| match p {
Either::Left(params) => Either::Left(&**params),
Either::Right(count) => Either::Right(*count),
})
}
/// Gets whether a column may be `NULL`, if this information is available.
pub fn nullable(&self, column: usize) -> Option<bool> {
self.nullable.get(column).copied().and_then(identity)
}
}
#[cfg(feature = "any")]
impl<DB: Database> Describe<DB> {
#[doc(hidden)]
pub fn try_into_any(self) -> crate::Result<Describe<crate::any::Any>>
where
crate::any::AnyColumn: for<'a> TryFrom<&'a DB::Column, Error = crate::Error>,
crate::any::AnyTypeInfo: for<'a> TryFrom<&'a DB::TypeInfo, Error = crate::Error>,
{
use crate::any::AnyTypeInfo;
let columns = self
.columns
.iter()
.map(crate::any::AnyColumn::try_from)
.collect::<Result<Vec<_>, _>>()?;
let parameters = match self.parameters {
Some(Either::Left(parameters)) => Some(Either::Left(
parameters
.iter()
.enumerate()
.map(|(i, type_info)| {
AnyTypeInfo::try_from(type_info).map_err(|_| {
crate::Error::AnyDriverError(
format!(
"Any driver does not support type {type_info} of parameter {i}"
)
.into(),
)
})
})
.collect::<Result<Vec<_>, _>>()?,
)),
Some(Either::Right(count)) => Some(Either::Right(count)),
None => None,
};
Ok(Describe {
columns,
parameters,
nullable: self.nullable,
})
}
}
+216
View File
@@ -0,0 +1,216 @@
//! Provides [`Encode`] for encoding values for the database.
use std::borrow::Cow;
use std::mem;
use std::rc::Rc;
use std::sync::Arc;
use crate::database::Database;
use crate::error::BoxDynError;
/// The return type of [Encode::encode].
#[must_use]
pub enum IsNull {
/// The value is null; no data was written.
Yes,
/// The value is not null.
///
/// This does not mean that data was written.
No,
}
impl IsNull {
pub fn is_null(&self) -> bool {
matches!(self, IsNull::Yes)
}
}
/// Encode a single value to be sent to the database.
pub trait Encode<'q, DB: Database> {
/// Writes the value of `self` into `buf` in the expected format for the database.
fn encode(self, buf: &mut <DB as Database>::ArgumentBuffer) -> Result<IsNull, BoxDynError>
where
Self: Sized,
{
self.encode_by_ref(buf)
}
/// Writes the value of `self` into `buf` without moving `self`.
///
/// Where possible, make use of `encode` instead as it can take advantage of re-using
/// memory.
fn encode_by_ref(
&self,
buf: &mut <DB as Database>::ArgumentBuffer,
) -> Result<IsNull, BoxDynError>;
fn produces(&self) -> Option<DB::TypeInfo> {
// `produces` is inherently a hook to allow database drivers to produce value-dependent
// type information; if the driver doesn't need this, it can leave this as `None`
None
}
#[inline]
fn size_hint(&self) -> usize {
mem::size_of_val(self)
}
}
impl<'q, T, DB: Database> Encode<'q, DB> for &'_ T
where
T: Encode<'q, DB>,
{
#[inline]
fn encode(self, buf: &mut <DB as Database>::ArgumentBuffer) -> Result<IsNull, BoxDynError> {
<T as Encode<DB>>::encode_by_ref(self, buf)
}
#[inline]
fn encode_by_ref(
&self,
buf: &mut <DB as Database>::ArgumentBuffer,
) -> Result<IsNull, BoxDynError> {
<&T as Encode<DB>>::encode(self, buf)
}
#[inline]
fn produces(&self) -> Option<DB::TypeInfo> {
(**self).produces()
}
#[inline]
fn size_hint(&self) -> usize {
(**self).size_hint()
}
}
#[macro_export]
macro_rules! impl_encode_for_option {
($DB:ident) => {
impl<'q, T> $crate::encode::Encode<'q, $DB> for Option<T>
where
T: $crate::encode::Encode<'q, $DB> + $crate::types::Type<$DB> + 'q,
{
#[inline]
fn produces(&self) -> Option<<$DB as $crate::database::Database>::TypeInfo> {
if let Some(v) = self {
v.produces()
} else {
T::type_info().into()
}
}
#[inline]
fn encode(
self,
buf: &mut <$DB as $crate::database::Database>::ArgumentBuffer,
) -> Result<$crate::encode::IsNull, $crate::error::BoxDynError> {
if let Some(v) = self {
v.encode(buf)
} else {
Ok($crate::encode::IsNull::Yes)
}
}
#[inline]
fn encode_by_ref(
&self,
buf: &mut <$DB as $crate::database::Database>::ArgumentBuffer,
) -> Result<$crate::encode::IsNull, $crate::error::BoxDynError> {
if let Some(v) = self {
v.encode_by_ref(buf)
} else {
Ok($crate::encode::IsNull::Yes)
}
}
#[inline]
fn size_hint(&self) -> usize {
self.as_ref().map_or(0, $crate::encode::Encode::size_hint)
}
}
};
}
macro_rules! impl_encode_for_smartpointer {
($smart_pointer:ty) => {
impl<'q, T, DB: Database> Encode<'q, DB> for $smart_pointer
where
T: Encode<'q, DB>,
{
#[inline]
fn encode(
self,
buf: &mut <DB as Database>::ArgumentBuffer,
) -> Result<IsNull, BoxDynError> {
<T as Encode<DB>>::encode_by_ref(self.as_ref(), buf)
}
#[inline]
fn encode_by_ref(
&self,
buf: &mut <DB as Database>::ArgumentBuffer,
) -> Result<IsNull, BoxDynError> {
<&T as Encode<DB>>::encode(self, buf)
}
#[inline]
fn produces(&self) -> Option<DB::TypeInfo> {
(**self).produces()
}
#[inline]
fn size_hint(&self) -> usize {
(**self).size_hint()
}
}
};
}
impl_encode_for_smartpointer!(Arc<T>);
impl_encode_for_smartpointer!(Box<T>);
impl_encode_for_smartpointer!(Rc<T>);
impl<'q, T, DB: Database> Encode<'q, DB> for Cow<'q, T>
where
T: Encode<'q, DB>,
T: ToOwned,
{
#[inline]
fn encode(self, buf: &mut <DB as Database>::ArgumentBuffer) -> Result<IsNull, BoxDynError> {
<&T as Encode<DB>>::encode_by_ref(&self.as_ref(), buf)
}
#[inline]
fn encode_by_ref(
&self,
buf: &mut <DB as Database>::ArgumentBuffer,
) -> Result<IsNull, BoxDynError> {
<&T as Encode<DB>>::encode_by_ref(&self.as_ref(), buf)
}
#[inline]
fn produces(&self) -> Option<DB::TypeInfo> {
<&T as Encode<DB>>::produces(&self.as_ref())
}
#[inline]
fn size_hint(&self) -> usize {
<&T as Encode<DB>>::size_hint(&self.as_ref())
}
}
#[macro_export]
macro_rules! forward_encode_impl {
($for_type:ty, $forward_to:ty, $db:ident) => {
impl<'q> Encode<'q, $db> for $for_type {
fn encode_by_ref(
&self,
buf: &mut <$db as sqlx_core::database::Database>::ArgumentBuffer,
) -> Result<IsNull, BoxDynError> {
<$forward_to as Encode<$db>>::encode(self.as_ref(), buf)
}
}
};
}
+353
View File
@@ -0,0 +1,353 @@
//! Types for working with errors produced by SQLx.
use std::any::type_name;
use std::borrow::Cow;
use std::error::Error as StdError;
use std::fmt::Display;
use std::io;
use crate::database::Database;
use crate::type_info::TypeInfo;
use crate::types::Type;
/// A specialized `Result` type for SQLx.
pub type Result<T, E = Error> = ::std::result::Result<T, E>;
// Convenience type alias for usage within SQLx.
// Do not make this type public.
pub type BoxDynError = Box<dyn StdError + 'static + Send + Sync>;
/// An unexpected `NULL` was encountered during decoding.
///
/// Returned from [`Row::get`](crate::row::Row::get) if the value from the database is `NULL`,
/// and you are not decoding into an `Option`.
#[derive(thiserror::Error, Debug)]
#[error("unexpected null; try decoding as an `Option`")]
pub struct UnexpectedNullError;
/// Represents all the ways a method can fail within SQLx.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
/// Error occurred while parsing a connection string.
#[error("error with configuration: {0}")]
Configuration(#[source] BoxDynError),
/// One or more of the arguments to the called function was invalid.
///
/// The string contains more information.
#[error("{0}")]
InvalidArgument(String),
/// Error returned from the database.
#[error("error returned from database: {0}")]
Database(#[source] Box<dyn DatabaseError>),
/// Error communicating with the database backend.
#[error("error communicating with database: {0}")]
Io(#[from] io::Error),
/// Error occurred while attempting to establish a TLS connection.
#[error("error occurred while attempting to establish a TLS connection: {0}")]
Tls(#[source] BoxDynError),
/// Unexpected or invalid data encountered while communicating with the database.
///
/// This should indicate there is a programming error in a SQLx driver or there
/// is something corrupted with the connection to the database itself.
#[error("encountered unexpected or invalid data: {0}")]
Protocol(String),
/// No rows returned by a query that expected to return at least one row.
#[error("no rows returned by a query that expected to return at least one row")]
RowNotFound,
/// Type in query doesn't exist. Likely due to typo or missing user type.
#[error("type named {type_name} not found")]
TypeNotFound { type_name: String },
/// Column index was out of bounds.
#[error("column index out of bounds: the len is {len}, but the index is {index}")]
ColumnIndexOutOfBounds { index: usize, len: usize },
/// No column found for the given name.
#[error("no column found for name: {0}")]
ColumnNotFound(String),
/// Error occurred while decoding a value from a specific column.
#[error("error occurred while decoding column {index}: {source}")]
ColumnDecode {
index: String,
#[source]
source: BoxDynError,
},
/// Error occurred while encoding a value.
#[error("error occurred while encoding a value: {0}")]
Encode(#[source] BoxDynError),
/// Error occurred while decoding a value.
#[error("error occurred while decoding: {0}")]
Decode(#[source] BoxDynError),
/// Error occurred within the `Any` driver mapping to/from the native driver.
#[error("error in Any driver mapping: {0}")]
AnyDriverError(#[source] BoxDynError),
/// A [`Pool::acquire`] timed out due to connections not becoming available or
/// because another task encountered too many errors while trying to open a new connection.
///
/// [`Pool::acquire`]: crate::pool::Pool::acquire
#[error("pool timed out while waiting for an open connection")]
PoolTimedOut,
/// [`Pool::close`] was called while we were waiting in [`Pool::acquire`].
///
/// [`Pool::acquire`]: crate::pool::Pool::acquire
/// [`Pool::close`]: crate::pool::Pool::close
#[error("attempted to acquire a connection on a closed pool")]
PoolClosed,
/// A background worker has crashed.
#[error("attempted to communicate with a crashed background worker")]
WorkerCrashed,
#[cfg(feature = "migrate")]
#[error("{0}")]
Migrate(#[source] Box<crate::migrate::MigrateError>),
#[error("attempted to call begin_with at non-zero transaction depth")]
InvalidSavePointStatement,
#[error("got unexpected connection status after attempting to begin transaction")]
BeginFailed,
// Not returned in normal operation.
/// Error occurred while reading configuration file
#[doc(hidden)]
#[error("error reading configuration file: {0}")]
ConfigFile(#[from] crate::config::ConfigError),
}
impl StdError for Box<dyn DatabaseError> {}
impl Error {
pub fn into_database_error(self) -> Option<Box<dyn DatabaseError + 'static>> {
match self {
Error::Database(err) => Some(err),
_ => None,
}
}
pub fn as_database_error(&self) -> Option<&(dyn DatabaseError + 'static)> {
match self {
Error::Database(err) => Some(&**err),
_ => None,
}
}
#[doc(hidden)]
#[inline]
pub fn protocol(err: impl Display) -> Self {
Error::Protocol(err.to_string())
}
#[doc(hidden)]
#[inline]
pub fn database(err: impl DatabaseError) -> Self {
Error::Database(Box::new(err))
}
#[doc(hidden)]
#[inline]
pub fn config(err: impl StdError + Send + Sync + 'static) -> Self {
Error::Configuration(err.into())
}
pub(crate) fn tls(err: impl Into<Box<dyn StdError + Send + Sync + 'static>>) -> Self {
Error::Tls(err.into())
}
#[doc(hidden)]
#[inline]
pub fn decode(err: impl Into<Box<dyn StdError + Send + Sync + 'static>>) -> Self {
Error::Decode(err.into())
}
}
pub fn mismatched_types<DB: Database, T: Type<DB>>(ty: &DB::TypeInfo) -> BoxDynError {
// TODO: `#name` only produces `TINYINT` but perhaps we want to show `TINYINT(1)`
format!(
"mismatched types; Rust type `{}` (as SQL type `{}`) is not compatible with SQL type `{}`",
type_name::<T>(),
T::type_info().name(),
ty.name()
)
.into()
}
/// The error kind.
///
/// This enum is to be used to identify frequent errors that can be handled by the program.
/// Although it currently only supports constraint violations, the type may grow in the future.
#[derive(Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ErrorKind {
/// Unique/primary key constraint violation.
UniqueViolation,
/// Foreign key constraint violation.
ForeignKeyViolation,
/// Not-null constraint violation.
NotNullViolation,
/// Check constraint violation.
CheckViolation,
/// Exclusion constraint violation.
ExclusionViolation,
/// An unmapped error.
Other,
}
/// An error that was returned from the database.
pub trait DatabaseError: 'static + Send + Sync + StdError {
/// The primary, human-readable error message.
fn message(&self) -> &str;
/// The (SQLSTATE) code for the error.
fn code(&self) -> Option<Cow<'_, str>> {
None
}
#[doc(hidden)]
fn as_error(&self) -> &(dyn StdError + Send + Sync + 'static);
#[doc(hidden)]
fn as_error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static);
#[doc(hidden)]
fn into_error(self: Box<Self>) -> Box<dyn StdError + Send + Sync + 'static>;
#[doc(hidden)]
fn is_transient_in_connect_phase(&self) -> bool {
false
}
/// Returns the name of the constraint that triggered the error, if applicable.
/// If the error was caused by a conflict of a unique index, this will be the index name.
///
/// ### Note
/// Currently only populated by the Postgres driver.
fn constraint(&self) -> Option<&str> {
None
}
/// Returns the name of the table that was affected by the error, if applicable.
///
/// ### Note
/// Currently only populated by the Postgres driver.
fn table(&self) -> Option<&str> {
None
}
/// Returns the kind of the error, if supported.
///
/// ### Note
/// Not all back-ends behave the same when reporting the error code.
fn kind(&self) -> ErrorKind;
/// Returns whether the error kind is a violation of a unique/primary key constraint.
fn is_unique_violation(&self) -> bool {
matches!(self.kind(), ErrorKind::UniqueViolation)
}
/// Returns whether the error kind is a violation of a foreign key.
fn is_foreign_key_violation(&self) -> bool {
matches!(self.kind(), ErrorKind::ForeignKeyViolation)
}
/// Returns whether the error kind is a violation of a check.
fn is_check_violation(&self) -> bool {
matches!(self.kind(), ErrorKind::CheckViolation)
}
}
impl dyn DatabaseError {
/// Downcast a reference to this generic database error to a specific
/// database error type.
///
/// # Panics
///
/// Panics if the database error type is not `E`. This is a deliberate contrast from
/// `Error::downcast_ref` which returns `Option<&E>`. In normal usage, you should know the
/// specific error type. In other cases, use `try_downcast_ref`.
pub fn downcast_ref<E: DatabaseError>(&self) -> &E {
self.try_downcast_ref().unwrap_or_else(|| {
panic!("downcast to wrong DatabaseError type; original error: {self}")
})
}
/// Downcast this generic database error to a specific database error type.
///
/// # Panics
///
/// Panics if the database error type is not `E`. This is a deliberate contrast from
/// `Error::downcast` which returns `Option<E>`. In normal usage, you should know the
/// specific error type. In other cases, use `try_downcast`.
pub fn downcast<E: DatabaseError>(self: Box<Self>) -> Box<E> {
self.try_downcast()
.unwrap_or_else(|e| panic!("downcast to wrong DatabaseError type; original error: {e}"))
}
/// Downcast a reference to this generic database error to a specific
/// database error type.
#[inline]
pub fn try_downcast_ref<E: DatabaseError>(&self) -> Option<&E> {
self.as_error().downcast_ref()
}
/// Downcast this generic database error to a specific database error type.
#[inline]
pub fn try_downcast<E: DatabaseError>(self: Box<Self>) -> Result<Box<E>, Box<Self>> {
if self.as_error().is::<E>() {
Ok(self.into_error().downcast().unwrap())
} else {
Err(self)
}
}
}
impl<E> From<E> for Error
where
E: DatabaseError,
{
#[inline]
fn from(error: E) -> Self {
Error::Database(Box::new(error))
}
}
#[cfg(feature = "migrate")]
impl From<crate::migrate::MigrateError> for Error {
#[inline]
fn from(error: crate::migrate::MigrateError) -> Self {
Error::Migrate(Box::new(error))
}
}
/// Format an error message as a `Protocol` error
#[macro_export]
macro_rules! err_protocol {
($($fmt_args:tt)*) => {
$crate::error::Error::Protocol(
format!(
"{} ({}:{})",
// Note: the format string needs to be unmodified (e.g. by `concat!()`)
// for implicit formatting arguments to work
format_args!($($fmt_args)*),
module_path!(),
line!(),
)
)
};
}
+284
View File
@@ -0,0 +1,284 @@
use crate::database::Database;
use crate::error::{BoxDynError, Error};
use crate::sql_str::{SqlSafeStr, SqlStr};
use either::Either;
use futures_core::future::BoxFuture;
use futures_core::stream::BoxStream;
use futures_util::{FutureExt, StreamExt, TryFutureExt, TryStreamExt};
use std::{fmt::Debug, future};
/// A type that contains or can provide a database
/// connection to use for executing queries against the database.
///
/// No guarantees are provided that successive queries run on the same
/// physical database connection.
///
/// A [`Connection`](crate::connection::Connection) is an `Executor` that guarantees that
/// successive queries are ran on the same physical database connection.
///
/// Implemented for the following:
///
/// * [`&Pool`](super::pool::Pool)
/// * [`&mut Connection`](super::connection::Connection)
///
/// The [`Executor`] impls for [`Transaction`](crate::transaction::Transaction)
/// and [`PoolConnection`](crate::pool::PoolConnection) have been deleted because they
/// cannot exist in the new crate architecture without rewriting the Executor trait entirely.
/// To fix this breakage, simply add a dereference where an impl [`Executor`] is expected, as
/// they both dereference to the inner connection type which will still implement it:
/// * `&mut transaction` -> `&mut *transaction`
/// * `&mut connection` -> `&mut *connection`
///
/// # Note: Methods Not for General Use
/// This is a building-block trait that is exposed mainly for use as a trait bound.
///
/// Instead of calling the methods of this trait, use the free functions in the `sqlx` crate root:
/// * [`sqlx::query()`]: use for DML queries (`SELECT`, `INSERT`, `UPDATE`, `DELETE`, etc.)
/// * uses and caches prepared statements internally per-connection
/// * may use argument placeholders (MySQL/MariaDB: `?`, Postgres/SQLite: `$1`, `$2`, etc.)
/// * one query per string
/// * [`sqlx::query_as()`], [`sqlx::query_scalar()`]: preferred for DML queries with type mapping
/// * [`sqlx::raw_sql()`]: for DDL (`CREATE`, `ALTER`, etc.), batch queries and administration functions
/// * accepts multiple queries separated by semicolons (`;`) in the same string
/// * never uses prepared statements
///
/// Consider also the `query!()` family of macros, which offer queries and type mapping checked
/// at compile-time.
///
/// [`sqlx::query()`]: crate::query::query
/// [`sqlx::query_as()`]: crate::query_as::query_as
/// [`sqlx::query_scalar()`]: crate::query_scalar::query_scalar
/// [`sqlx::raw_sql()`]: crate::raw_sql::raw_sql
pub trait Executor<'c>: Send + Debug + Sized {
type Database: Database;
/// Execute the query and return the total number of rows affected.
fn execute<'e, 'q: 'e, E>(
self,
query: E,
) -> BoxFuture<'e, Result<<Self::Database as Database>::QueryResult, Error>>
where
'c: 'e,
E: 'q + Execute<'q, Self::Database>,
{
self.execute_many(query).try_collect().boxed()
}
/// Execute multiple queries and return the rows affected from each query, in a stream.
fn execute_many<'e, 'q: 'e, E>(
self,
query: E,
) -> BoxStream<'e, Result<<Self::Database as Database>::QueryResult, Error>>
where
'c: 'e,
E: 'q + Execute<'q, Self::Database>,
{
self.fetch_many(query)
.try_filter_map(|step| async move {
Ok(match step {
Either::Left(rows) => Some(rows),
Either::Right(_) => None,
})
})
.boxed()
}
/// Execute the query and return the generated results as a stream.
fn fetch<'e, 'q: 'e, E>(
self,
query: E,
) -> BoxStream<'e, Result<<Self::Database as Database>::Row, Error>>
where
'c: 'e,
E: 'q + Execute<'q, Self::Database>,
{
self.fetch_many(query)
.try_filter_map(|step| async move {
Ok(match step {
Either::Left(_) => None,
Either::Right(row) => Some(row),
})
})
.boxed()
}
/// Execute multiple queries and return the generated results as a stream
/// from each query, in a stream.
fn fetch_many<'e, 'q: 'e, E>(
self,
query: E,
) -> BoxStream<
'e,
Result<
Either<<Self::Database as Database>::QueryResult, <Self::Database as Database>::Row>,
Error,
>,
>
where
'c: 'e,
E: 'q + Execute<'q, Self::Database>;
/// Execute the query and return all the generated results, collected into a [`Vec`].
fn fetch_all<'e, 'q: 'e, E>(
self,
query: E,
) -> BoxFuture<'e, Result<Vec<<Self::Database as Database>::Row>, Error>>
where
'c: 'e,
E: 'q + Execute<'q, Self::Database>,
{
self.fetch(query).try_collect().boxed()
}
/// Execute the query and returns exactly one row.
fn fetch_one<'e, 'q: 'e, E>(
self,
query: E,
) -> BoxFuture<'e, Result<<Self::Database as Database>::Row, Error>>
where
'c: 'e,
E: 'q + Execute<'q, Self::Database>,
{
self.fetch_optional(query)
.and_then(|row| {
future::ready(match row {
Some(row) => Ok(row),
None => Err(Error::RowNotFound),
})
})
.boxed()
}
/// Execute the query and returns at most one row.
fn fetch_optional<'e, 'q: 'e, E>(
self,
query: E,
) -> BoxFuture<'e, Result<Option<<Self::Database as Database>::Row>, Error>>
where
'c: 'e,
E: 'q + Execute<'q, Self::Database>;
/// Prepare the SQL query to inspect the type information of its parameters
/// and results.
///
/// Be advised that when using the `query`, `query_as`, or `query_scalar` functions, the query
/// is transparently prepared and executed.
///
/// This explicit API is provided to allow access to the statement metadata available after
/// it prepared but before the first row is returned.
#[inline]
fn prepare<'e>(
self,
query: SqlStr,
) -> BoxFuture<'e, Result<<Self::Database as Database>::Statement, Error>>
where
'c: 'e,
{
self.prepare_with(query, &[])
}
/// Prepare the SQL query, with parameter type information, to inspect the
/// type information about its parameters and results.
///
/// Only some database drivers (PostgreSQL, MSSQL) can take advantage of
/// this extra information to influence parameter type inference.
fn prepare_with<'e>(
self,
sql: SqlStr,
parameters: &'e [<Self::Database as Database>::TypeInfo],
) -> BoxFuture<'e, Result<<Self::Database as Database>::Statement, Error>>
where
'c: 'e;
/// Describe the SQL query and return type information about its parameters
/// and results.
///
/// This is used by compile-time verification in the query macros to
/// power their type inference.
#[doc(hidden)]
#[cfg(feature = "offline")]
fn describe<'e>(
self,
sql: SqlStr,
) -> BoxFuture<'e, Result<crate::describe::Describe<Self::Database>, Error>>
where
'c: 'e;
}
/// A type that may be executed against a database connection.
///
/// Implemented for the following:
///
/// * [`&str`](std::str)
/// * [`Query`](super::query::Query)
///
pub trait Execute<'q, DB: Database>: Send + Sized {
/// Gets the SQL that will be executed.
fn sql(self) -> SqlStr;
/// Gets the previously cached statement, if available.
fn statement(&self) -> Option<&DB::Statement>;
/// Returns the arguments to be bound against the query string.
///
/// Returning `Ok(None)` for `Arguments` indicates to use a "simple" query protocol and to not
/// prepare the query. Returning `Ok(Some(Default::default()))` is an empty arguments object that
/// will be prepared (and cached) before execution.
///
/// Returns `Err` if encoding any of the arguments failed.
fn take_arguments(&mut self) -> Result<Option<<DB as Database>::Arguments>, BoxDynError>;
/// Returns `true` if the statement should be cached.
fn persistent(&self) -> bool;
}
impl<DB: Database, T> Execute<'_, DB> for T
where
T: SqlSafeStr + Send,
{
#[inline]
fn sql(self) -> SqlStr {
self.into_sql_str()
}
#[inline]
fn statement(&self) -> Option<&DB::Statement> {
None
}
#[inline]
fn take_arguments(&mut self) -> Result<Option<<DB as Database>::Arguments>, BoxDynError> {
Ok(None)
}
#[inline]
fn persistent(&self) -> bool {
true
}
}
impl<DB: Database, T> Execute<'_, DB> for (T, Option<<DB as Database>::Arguments>)
where
T: SqlSafeStr + Send,
{
#[inline]
fn sql(self) -> SqlStr {
self.0.into_sql_str()
}
#[inline]
fn statement(&self) -> Option<&DB::Statement> {
None
}
#[inline]
fn take_arguments(&mut self) -> Result<Option<<DB as Database>::Arguments>, BoxDynError> {
Ok(self.1.take())
}
#[inline]
fn persistent(&self) -> bool {
true
}
}
+138
View File
@@ -0,0 +1,138 @@
//! A minimalist clone of the `async-stream` crate in 100% safe code, without proc macros.
//!
//! This was created initially to get around some weird compiler errors we were getting with
//! `async-stream`, and now it'd just be more work to replace.
use std::future::{self, Future};
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};
use futures_core::future::BoxFuture;
use futures_core::stream::Stream;
use futures_core::FusedFuture;
use futures_util::future::Fuse;
use futures_util::FutureExt;
use crate::error::Error;
pub struct TryAsyncStream<'a, T> {
yielder: Yielder<T>,
future: Fuse<BoxFuture<'a, Result<(), Error>>>,
}
impl<'a, T> TryAsyncStream<'a, T> {
pub fn new<F, Fut>(f: F) -> Self
where
F: FnOnce(Yielder<T>) -> Fut + Send,
Fut: 'a + Future<Output = Result<(), Error>> + Send,
T: 'a + Send,
{
let yielder = Yielder::new();
let future = f(yielder.duplicate()).boxed().fuse();
Self { future, yielder }
}
}
pub struct Yielder<T> {
// This mutex should never have any contention in normal operation.
// We're just using it because `Rc<Cell<Option<T>>>` would not be `Send`.
value: Arc<Mutex<Option<T>>>,
}
impl<T> Yielder<T> {
fn new() -> Self {
Yielder {
value: Arc::new(Mutex::new(None)),
}
}
// Don't want to expose a `Clone` impl
fn duplicate(&self) -> Self {
Yielder {
value: self.value.clone(),
}
}
/// NOTE: may deadlock the task if called from outside the future passed to `TryAsyncStream`.
pub async fn r#yield(&self, val: T) {
let replaced = self
.value
.lock()
.expect("BUG: panicked while holding a lock")
.replace(val);
debug_assert!(
replaced.is_none(),
"BUG: previously yielded value not taken"
);
let mut yielded = false;
// Allows the generating future to suspend its execution without changing the task priority,
// which would happen with `tokio::task::yield_now()`.
//
// Note that because this has no way to schedule a wakeup, this could deadlock the task
// if called in the wrong place.
future::poll_fn(|_cx| {
if !yielded {
yielded = true;
Poll::Pending
} else {
Poll::Ready(())
}
})
.await
}
fn take(&self) -> Option<T> {
self.value
.lock()
.expect("BUG: panicked while holding a lock")
.take()
}
}
impl<T> Stream for TryAsyncStream<'_, T> {
type Item = Result<T, Error>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
if self.future.is_terminated() {
return Poll::Ready(None);
}
match self.future.poll_unpin(cx) {
Poll::Ready(Ok(())) => {
// Future returned without yielding another value,
// or else it would have returned `Pending` instead.
Poll::Ready(None)
}
Poll::Ready(Err(e)) => Poll::Ready(Some(Err(e))),
Poll::Pending => self
.yielder
.take()
.map_or(Poll::Pending, |val| Poll::Ready(Some(Ok(val)))),
}
}
}
#[macro_export]
macro_rules! try_stream {
($($block:tt)*) => {
$crate::ext::async_stream::TryAsyncStream::new(move |yielder| ::tracing::Instrument::in_current_span(async move {
// Anti-footgun: effectively pins `yielder` to this future to prevent any accidental
// move to another task, which could deadlock.
let yielder = &yielder;
macro_rules! r#yield {
($v:expr) => {{
yielder.r#yield($v).await;
}}
}
$($block)*
}))
}
}
+4
View File
@@ -0,0 +1,4 @@
pub mod ustr;
#[macro_use]
pub mod async_stream;
+121
View File
@@ -0,0 +1,121 @@
use std::borrow::Borrow;
use std::fmt::{self, Debug, Display, Formatter};
use std::hash::{Hash, Hasher};
use std::ops::Deref;
use std::sync::Arc;
// U meaning micro
// a micro-string is either a reference-counted string or a static string
// this guarantees these are cheap to clone everywhere
#[derive(Clone, Eq)]
pub enum UStr {
Static(&'static str),
Shared(Arc<str>),
}
impl UStr {
pub fn new(s: &str) -> Self {
UStr::Shared(Arc::from(s.to_owned()))
}
/// Apply [str::strip_prefix], without copying if possible.
pub fn strip_prefix(this: &Self, prefix: &str) -> Option<Self> {
match this {
UStr::Static(s) => s.strip_prefix(prefix).map(Self::Static),
UStr::Shared(s) => s.strip_prefix(prefix).map(|s| Self::Shared(s.into())),
}
}
}
impl Deref for UStr {
type Target = str;
#[inline]
fn deref(&self) -> &str {
match self {
UStr::Static(s) => s,
UStr::Shared(s) => s,
}
}
}
impl Hash for UStr {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
// Forward the hash to the string representation of this
// A derive(Hash) encodes the enum discriminant
(**self).hash(state);
}
}
impl Borrow<str> for UStr {
#[inline]
fn borrow(&self) -> &str {
self
}
}
impl PartialEq<UStr> for UStr {
fn eq(&self, other: &UStr) -> bool {
(**self).eq(&**other)
}
}
impl From<&'static str> for UStr {
#[inline]
fn from(s: &'static str) -> Self {
UStr::Static(s)
}
}
impl<'a> From<&'a UStr> for UStr {
fn from(value: &'a UStr) -> Self {
value.clone()
}
}
impl From<String> for UStr {
#[inline]
fn from(s: String) -> Self {
UStr::Shared(s.into())
}
}
impl Debug for UStr {
#[inline]
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.pad(self)
}
}
impl Display for UStr {
#[inline]
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.pad(self)
}
}
// manual impls because otherwise things get a little screwy with lifetimes
#[cfg(feature = "offline")]
impl<'de> serde::Deserialize<'de> for UStr {
fn deserialize<D>(deserializer: D) -> Result<Self, <D as serde::Deserializer<'de>>::Error>
where
D: serde::Deserializer<'de>,
{
Ok(String::deserialize(deserializer)?.into())
}
}
#[cfg(feature = "offline")]
impl serde::Serialize for UStr {
fn serialize<S>(
&self,
serializer: S,
) -> Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(self)
}
}
+524
View File
@@ -0,0 +1,524 @@
use crate::{error::Error, row::Row};
/// A record that can be built from a row returned by the database.
///
/// In order to use [`query_as`](crate::query_as) the output type must implement `FromRow`.
///
/// ## Derivable
///
/// This trait can be derived by SQLx for any struct. The generated implementation
/// will consist of a sequence of calls to [`Row::try_get`] using the name from each
/// struct field.
///
/// ```rust,ignore
/// #[derive(sqlx::FromRow)]
/// struct User {
/// id: i32,
/// name: String,
/// }
/// ```
///
/// ### Field attributes
///
/// Several attributes can be specified to customize how each column in a row is read:
///
/// #### `rename`
///
/// When the name of a field in Rust does not match the name of its corresponding column,
/// you can use the `rename` attribute to specify the name that the field has in the row.
/// For example:
///
/// ```rust,ignore
/// #[derive(sqlx::FromRow)]
/// struct User {
/// id: i32,
/// name: String,
/// #[sqlx(rename = "description")]
/// about_me: String
/// }
/// ```
///
/// Given a query such as:
///
/// ```sql
/// SELECT id, name, description FROM users;
/// ```
///
/// will read the content of the column `description` into the field `about_me`.
///
/// #### `rename_all`
/// By default, field names are expected verbatim (with the exception of the raw identifier prefix `r#`, if present).
/// Placed at the struct level, this attribute changes how the field name is mapped to its SQL column name:
///
/// ```rust,ignore
/// #[derive(sqlx::FromRow)]
/// #[sqlx(rename_all = "camelCase")]
/// struct UserPost {
/// id: i32,
/// // remapped to "userId"
/// user_id: i32,
/// contents: String
/// }
/// ```
///
/// The supported values are `snake_case` (available if you have non-snake-case field names for some
/// reason), `lowercase`, `UPPERCASE`, `camelCase`, `PascalCase`, `SCREAMING_SNAKE_CASE` and `kebab-case`.
/// The styling of each option is intended to be an example of its behavior.
///
/// Case conversion is handled by the `heck` crate.
/// See [its documentation](https://docs.rs/heck/0.5.0/heck/#definition-of-a-word-boundary)
/// for details.
///
/// Note that numbers are *not* considered separate words.
/// For example, `Foo1` to snake case would be `foo1`, *not* `foo_1`.
/// See [this issue](https://github.com/launchbadge/sqlx/issues/3864) for discussion.
///
/// #### `default`
///
/// When your struct contains a field that is not present in your query,
/// if the field type has an implementation for [`Default`],
/// you can use the `default` attribute to assign the default value to said field.
/// For example:
///
/// ```rust,ignore
/// #[derive(sqlx::FromRow)]
/// struct User {
/// id: i32,
/// name: String,
/// #[sqlx(default)]
/// location: Option<String>
/// }
/// ```
///
/// Given a query such as:
///
/// ```sql
/// SELECT id, name FROM users;
/// ```
///
/// will set the value of the field `location` to the default value of `Option<String>`,
/// which is `None`.
///
/// Moreover, if the struct has an implementation for [`Default`], you can use the `default`
/// attribute at the struct level rather than for each single field. If a field does not appear in the result,
/// its value is taken from the `Default` implementation for the struct.
/// For example:
///
/// ```rust, ignore
/// #[derive(Default, sqlx::FromRow)]
/// #[sqlx(default)]
/// struct Options {
/// option_a: Option<i32>,
/// option_b: Option<String>,
/// option_c: Option<bool>,
/// }
/// ```
///
/// For a derived `Default` implementation this effectively populates each missing field
/// with `Default::default()`, but a manual `Default` implementation can provide
/// different placeholder values, if applicable.
///
/// This is similar to how `#[serde(default)]` behaves.
///
/// #### `flatten`
///
/// If you want to handle a field that implements [`FromRow`],
/// you can use the `flatten` attribute to specify that you want
/// it to use [`FromRow`] for parsing rather than the usual method.
/// For example:
///
/// ```rust,ignore
/// #[derive(sqlx::FromRow)]
/// struct Address {
/// country: String,
/// city: String,
/// road: String,
/// }
///
/// #[derive(sqlx::FromRow)]
/// struct User {
/// id: i32,
/// name: String,
/// #[sqlx(flatten)]
/// address: Address,
/// }
/// ```
/// Given a query such as:
///
/// ```sql
/// SELECT id, name, country, city, road FROM users;
/// ```
///
/// This field is compatible with the `default` attribute.
///
/// #### `skip`
///
/// This is a variant of the `default` attribute which instead always takes the value from
/// the `Default` implementation for this field type ignoring any results in your query.
/// This can be useful, if some field does not satifisfy the trait bounds (i.e.
/// `sqlx::decode::Decode`, `sqlx::type::Type`), in particular in case of nested structures.
/// For example:
///
/// ```rust,ignore
/// #[derive(sqlx::FromRow)]
/// struct Address {
/// user_name: String,
/// street: String,
/// city: String,
/// }
///
/// #[derive(sqlx::FromRow)]
/// struct User {
/// name: String,
/// #[sqlx(skip)]
/// addresses: Vec<Address>,
/// }
/// ```
///
/// Then when querying into `User`, only `name` needs to be set:
///
/// ```rust,ignore
/// let user: User = sqlx::query_as("SELECT name FROM users")
/// .fetch_one(&mut some_connection)
/// .await?;
///
/// // `Default` for `Vec<Address>` is an empty vector.
/// assert!(user.addresses.is_empty());
/// ```
///
/// #### `try_from`
///
/// When your struct contains a field whose type is not matched with the database type,
/// if the field type has an implementation [`TryFrom`] for the database type,
/// you can use the `try_from` attribute to convert the database type to the field type.
/// For example:
///
/// ```rust,ignore
/// #[derive(sqlx::FromRow)]
/// struct User {
/// id: i32,
/// name: String,
/// #[sqlx(try_from = "i64")]
/// bigIntInMySql: u64
/// }
/// ```
///
/// Given a query such as:
///
/// ```sql
/// SELECT id, name, bigIntInMySql FROM users;
/// ```
///
/// In MySql, `BigInt` type matches `i64`, but you can convert it to `u64` by `try_from`.
///
/// #### `json`
///
/// If your database supports a JSON type, you can leverage `#[sqlx(json)]`
/// to automatically integrate JSON deserialization in your [`FromRow`] implementation using [`serde`](https://docs.rs/serde/latest/serde/).
///
/// ```rust,ignore
/// #[derive(serde::Deserialize)]
/// struct Data {
/// field1: String,
/// field2: u64
/// }
///
/// #[derive(sqlx::FromRow)]
/// struct User {
/// id: i32,
/// name: String,
/// #[sqlx(json)]
/// metadata: Data
/// }
/// ```
///
/// Given a query like the following:
///
/// ```sql
/// SELECT
/// 1 AS id,
/// 'Name' AS name,
/// JSON_OBJECT('field1', 'value1', 'field2', 42) AS metadata
/// ```
///
/// The `metadata` field will be deserialized used its `serde::Deserialize` implementation:
///
/// ```rust,ignore
/// User {
/// id: 1,
/// name: "Name",
/// metadata: Data {
/// field1: "value1",
/// field2: 42
/// }
/// }
/// ```
///
/// By default the `#[sqlx(json)]` attribute will assume that the underlying database row is
/// _not_ NULL. This can cause issues when your field type is an `Option<T>` because this would be
/// represented as the _not_ NULL (in terms of DB) JSON value of `null`.
///
/// If you wish to describe a database row which _is_ NULLable but _cannot_ contain the JSON value `null`,
/// use the `#[sqlx(json(nullable))]` attribute.
///
/// For example
/// ```rust,ignore
/// #[derive(serde::Deserialize)]
/// struct Data {
/// field1: String,
/// field2: u64
/// }
///
/// #[derive(sqlx::FromRow)]
/// struct User {
/// id: i32,
/// name: String,
/// #[sqlx(json(nullable))]
/// metadata: Option<Data>
/// }
/// ```
/// Would describe a database field which _is_ NULLable but if it exists it must be the JSON representation of `Data`
/// and cannot be the JSON value `null`
///
/// ## Manual implementation
///
/// You can also implement the [`FromRow`] trait by hand. This can be useful if you
/// have a struct with a field that needs manual decoding:
///
///
/// ```rust,ignore
/// use sqlx::{FromRow, sqlite::SqliteRow, sqlx::Row};
/// struct MyCustomType {
/// custom: String,
/// }
///
/// struct Foo {
/// bar: MyCustomType,
/// }
///
/// impl FromRow<'_, SqliteRow> for Foo {
/// fn from_row(row: &SqliteRow) -> sqlx::Result<Self> {
/// Ok(Self {
/// bar: MyCustomType {
/// custom: row.try_get("custom")?
/// }
/// })
/// }
/// }
/// ```
pub trait FromRow<'r, R: Row>: Sized {
fn from_row(row: &'r R) -> Result<Self, Error>;
}
impl<'r, R> FromRow<'r, R> for ()
where
R: Row,
{
#[inline]
fn from_row(_: &'r R) -> Result<Self, Error> {
Ok(())
}
}
// implement FromRow for tuples of types that implement Decode
// up to tuples of 16 values
macro_rules! impl_from_row_for_tuple {
($( ($idx:tt) -> $T:ident );+;) => {
impl<'r, R, $($T,)+> FromRow<'r, R> for ($($T,)+)
where
R: Row,
usize: crate::column::ColumnIndex<R>,
$($T: crate::decode::Decode<'r, R::Database> + crate::types::Type<R::Database>,)+
{
#[inline]
fn from_row(row: &'r R) -> Result<Self, Error> {
Ok(($(row.try_get($idx as usize)?,)+))
}
}
};
}
impl_from_row_for_tuple!(
(0) -> T1;
);
impl_from_row_for_tuple!(
(0) -> T1;
(1) -> T2;
);
impl_from_row_for_tuple!(
(0) -> T1;
(1) -> T2;
(2) -> T3;
);
impl_from_row_for_tuple!(
(0) -> T1;
(1) -> T2;
(2) -> T3;
(3) -> T4;
);
impl_from_row_for_tuple!(
(0) -> T1;
(1) -> T2;
(2) -> T3;
(3) -> T4;
(4) -> T5;
);
impl_from_row_for_tuple!(
(0) -> T1;
(1) -> T2;
(2) -> T3;
(3) -> T4;
(4) -> T5;
(5) -> T6;
);
impl_from_row_for_tuple!(
(0) -> T1;
(1) -> T2;
(2) -> T3;
(3) -> T4;
(4) -> T5;
(5) -> T6;
(6) -> T7;
);
impl_from_row_for_tuple!(
(0) -> T1;
(1) -> T2;
(2) -> T3;
(3) -> T4;
(4) -> T5;
(5) -> T6;
(6) -> T7;
(7) -> T8;
);
impl_from_row_for_tuple!(
(0) -> T1;
(1) -> T2;
(2) -> T3;
(3) -> T4;
(4) -> T5;
(5) -> T6;
(6) -> T7;
(7) -> T8;
(8) -> T9;
);
impl_from_row_for_tuple!(
(0) -> T1;
(1) -> T2;
(2) -> T3;
(3) -> T4;
(4) -> T5;
(5) -> T6;
(6) -> T7;
(7) -> T8;
(8) -> T9;
(9) -> T10;
);
impl_from_row_for_tuple!(
(0) -> T1;
(1) -> T2;
(2) -> T3;
(3) -> T4;
(4) -> T5;
(5) -> T6;
(6) -> T7;
(7) -> T8;
(8) -> T9;
(9) -> T10;
(10) -> T11;
);
impl_from_row_for_tuple!(
(0) -> T1;
(1) -> T2;
(2) -> T3;
(3) -> T4;
(4) -> T5;
(5) -> T6;
(6) -> T7;
(7) -> T8;
(8) -> T9;
(9) -> T10;
(10) -> T11;
(11) -> T12;
);
impl_from_row_for_tuple!(
(0) -> T1;
(1) -> T2;
(2) -> T3;
(3) -> T4;
(4) -> T5;
(5) -> T6;
(6) -> T7;
(7) -> T8;
(8) -> T9;
(9) -> T10;
(10) -> T11;
(11) -> T12;
(12) -> T13;
);
impl_from_row_for_tuple!(
(0) -> T1;
(1) -> T2;
(2) -> T3;
(3) -> T4;
(4) -> T5;
(5) -> T6;
(6) -> T7;
(7) -> T8;
(8) -> T9;
(9) -> T10;
(10) -> T11;
(11) -> T12;
(12) -> T13;
(13) -> T14;
);
impl_from_row_for_tuple!(
(0) -> T1;
(1) -> T2;
(2) -> T3;
(3) -> T4;
(4) -> T5;
(5) -> T6;
(6) -> T7;
(7) -> T8;
(8) -> T9;
(9) -> T10;
(10) -> T11;
(11) -> T12;
(12) -> T13;
(13) -> T14;
(14) -> T15;
);
impl_from_row_for_tuple!(
(0) -> T1;
(1) -> T2;
(2) -> T3;
(3) -> T4;
(4) -> T5;
(5) -> T6;
(6) -> T7;
(7) -> T8;
(8) -> T9;
(9) -> T10;
(10) -> T11;
(11) -> T12;
(12) -> T13;
(13) -> T14;
(14) -> T15;
(15) -> T16;
);
Vendored Executable
+96
View File
@@ -0,0 +1,96 @@
use std::ffi::OsString;
use std::fs::Metadata;
use std::io;
use std::path::{Path, PathBuf};
use crate::rt;
pub struct ReadDir {
inner: Option<std::fs::ReadDir>,
}
pub struct DirEntry {
pub path: PathBuf,
pub file_name: OsString,
pub metadata: Metadata,
}
// Filesystem operations are generally not capable of being non-blocking
// so Tokio and async-std don't bother; they just send the work to a blocking thread pool.
//
// We save on code duplication here by just implementing the same strategy ourselves
// using the runtime's `spawn_blocking()` primitive.
pub async fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
let path = PathBuf::from(path.as_ref());
rt::spawn_blocking(move || std::fs::read(path)).await
}
pub async fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
let path = PathBuf::from(path.as_ref());
rt::spawn_blocking(move || std::fs::read_to_string(path)).await
}
pub async fn create_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
let path = PathBuf::from(path.as_ref());
rt::spawn_blocking(move || std::fs::create_dir_all(path)).await
}
pub async fn remove_file<P: AsRef<Path>>(path: P) -> io::Result<()> {
let path = PathBuf::from(path.as_ref());
rt::spawn_blocking(move || std::fs::remove_file(path)).await
}
pub async fn remove_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
let path = PathBuf::from(path.as_ref());
rt::spawn_blocking(move || std::fs::remove_dir(path)).await
}
pub async fn remove_dir_all<P: AsRef<Path>>(path: P) -> io::Result<()> {
let path = PathBuf::from(path.as_ref());
rt::spawn_blocking(move || std::fs::remove_dir_all(path)).await
}
pub async fn read_dir(path: PathBuf) -> io::Result<ReadDir> {
let read_dir = rt::spawn_blocking(move || std::fs::read_dir(path)).await?;
Ok(ReadDir {
inner: Some(read_dir),
})
}
impl ReadDir {
pub async fn next(&mut self) -> io::Result<Option<DirEntry>> {
if let Some(mut read_dir) = self.inner.take() {
let maybe = rt::spawn_blocking(move || {
let entry = read_dir.next().transpose()?;
entry
.map(|entry| -> io::Result<_> {
Ok((
read_dir,
DirEntry {
path: entry.path(),
file_name: entry.file_name(),
// We always want the metadata as well so might as well fetch
// it in the same blocking call.
metadata: entry.metadata()?,
},
))
})
.transpose()
})
.await?;
match maybe {
Some((read_dir, entry)) => {
self.inner = Some(read_dir);
Ok(Some(entry))
}
None => Ok(None),
}
} else {
Ok(None)
}
}
}
+58
View File
@@ -0,0 +1,58 @@
use std::str::from_utf8;
use bytes::{Buf, Bytes};
use memchr::memchr;
use crate::error::Error;
pub trait BufExt: Buf {
// Read a nul-terminated byte sequence
fn get_bytes_nul(&mut self) -> Result<Bytes, Error>;
// Read a byte sequence of the exact length
fn get_bytes(&mut self, len: usize) -> Bytes;
// Read a nul-terminated string
fn get_str_nul(&mut self) -> Result<String, Error>;
// Read a string of the exact length
fn get_str(&mut self, len: usize) -> Result<String, Error>;
}
impl BufExt for Bytes {
fn get_bytes_nul(&mut self) -> Result<Bytes, Error> {
let nul =
memchr(b'\0', self).ok_or_else(|| err_protocol!("expected NUL in byte sequence"))?;
let v = self.slice(0..nul);
self.advance(nul + 1);
Ok(v)
}
fn get_bytes(&mut self, len: usize) -> Bytes {
let v = self.slice(..len);
self.advance(len);
v
}
fn get_str_nul(&mut self) -> Result<String, Error> {
self.get_bytes_nul().and_then(|bytes| {
from_utf8(&bytes)
.map(ToOwned::to_owned)
.map_err(|err| err_protocol!("{}", err))
})
}
fn get_str(&mut self, len: usize) -> Result<String, Error> {
let v = from_utf8(&self[..len])
.map_err(|err| err_protocol!("{}", err))
.map(ToOwned::to_owned)?;
self.advance(len);
Ok(v)
}
}
Loaded 100 of 155 files, more files were not shown because too many files have changed in this diff. Show more