feat: harden community production foundation through story 1.5

This commit is contained in:
bsodfather committed 2026-08-14 00:21:59 +03:00
1 parent c30461cc92
commit f6fc2e5c9b
161 files changed
+16758 -2515

No files matched your search

@@ -0,0 +1,926 @@
use std::fmt;
use sha2::{Digest, Sha256};
use sqlx::{PgConnection, PgPool, Row, Transaction, query};
use super::schema_guard::{
OWNED_RELATIONS, relation_exists, validate_required_relations, validate_schema_fingerprint,
};
use super::{BASELINE_CHECKSUM, BASELINE_VERSION, apply_baseline};
use crate::ext::ExtensionMigration;
const MIGRATION_LOCK_ID: i64 = 0x4352_414E_4B4D_4947;
const CURRENT_VERSION: i64 = 3;
const IMPLEMENTED_VERSIONS: &[i64] = &[1, 2, 3];
const BASELINE_SOURCE_SHA256: &str =
"eb1656fc5b4b5be9ee390d237d1d58e4b2274ae5ba9b7ba06a2f3f860dfda675";
const CONSOLIDATION_SOURCE: &str = include_str!("consolidation_v2.sql");
const CONSOLIDATION_SOURCE_SHA256: &str =
"1908b97ca7fe8a85d146b0eebf007d5018a9ff406cb099614270f3428ec1db48";
const REQUEST_TRACE_IDENTITY_SOURCE: &str = include_str!("request_trace_identity_v3.sql");
const REQUEST_TRACE_IDENTITY_SOURCE_SHA256: &str =
"36487625503a8d4d8f18d5771c3c9b6705f845e267acbfcb7244c330f640cd94";
const BASELINE_RELATIONS: &[&str] = &[
"workspaces",
"users",
"memberships",
"user_sessions",
"invitation_tokens",
"platform_api_keys",
"operations",
"operation_versions",
"published_operations",
"operation_samples",
"descriptors",
"agents",
"agent_versions",
"published_agents",
"agent_operation_bindings",
"secrets",
"secret_versions",
"auth_profiles",
"workspace_upstreams",
"yaml_import_jobs",
"import_jobs",
"approval_requests",
"invocation_logs",
"usage_rollups",
];
const CONSOLIDATION_RELATIONS: &[&str] = &[
"__crank_migrations",
"__crank_migration_legacy_audit",
"__crank_mcp_migrations",
"mcp_transport_sessions",
"__crank_ext_migrations",
];
const REGISTERED_EXTENSION_MIGRATIONS: &[(&str, ExtensionMigration)] = &[];
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MigrationDescriptor {
pub version: i64,
pub name: &'static str,
pub checksum: String,
pub source_digest: String,
pub phase: &'static str,
pub compatibility: &'static str,
pub owner: &'static str,
pub transactional: bool,
pub backfill: BackfillPolicy,
pub readable_schema_min: i64,
pub readable_schema_max: i64,
pub contract_evidence: Option<&'static str>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BackfillPolicy {
None,
Bounded {
max_batch_rows: u32,
max_batch_ms: u32,
resumable: bool,
},
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BackfillBatch {
pub cursor: Option<String>,
pub max_rows: u32,
pub max_ms: u32,
}
impl BackfillBatch {
pub fn validate(&self, policy: BackfillPolicy) -> Result<(), MigrationError> {
match policy {
BackfillPolicy::Bounded {
max_batch_rows,
max_batch_ms,
resumable: true,
} if (1..=max_batch_rows).contains(&self.max_rows)
&& (1..=max_batch_ms).contains(&self.max_ms)
&& self
.cursor
.as_ref()
.is_none_or(|cursor| cursor.len() <= 256) =>
{
Ok(())
}
_ => Err(MigrationError::new(
"invalid_contract",
"contract.backfill",
None,
"contact_operator",
)),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MigrationPreflight {
Current { version: i64 },
MigrationRequired { current: i64, target: i64 },
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MigrationApplyResult {
Applied { from: i64, to: i64 },
AlreadyCurrent { version: i64 },
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MigrationError {
code: &'static str,
stage: &'static str,
version: Option<i64>,
recovery: &'static str,
}
impl MigrationError {
pub(super) fn new(
code: &'static str,
stage: &'static str,
version: Option<i64>,
recovery: &'static str,
) -> Self {
Self {
code,
stage,
version,
recovery,
}
}
pub(super) fn storage(stage: &'static str) -> Self {
Self::new("storage_unavailable", stage, None, "contact_operator")
}
pub fn code(&self) -> &'static str {
self.code
}
pub fn stage(&self) -> &'static str {
self.stage
}
pub fn version(&self) -> Option<i64> {
self.version
}
pub fn recovery(&self) -> &'static str {
self.recovery
}
}
impl fmt::Display for MigrationError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
formatter,
"migration_error code={} stage={} version={} recovery={}",
self.code,
self.stage,
self.version
.map_or_else(|| "none".to_owned(), |value| value.to_string()),
self.recovery
)
}
}
impl std::error::Error for MigrationError {}
pub struct MigrationAuthority;
impl MigrationAuthority {
pub fn registered_extension_migrations() -> &'static [(&'static str, ExtensionMigration)] {
REGISTERED_EXTENSION_MIGRATIONS
}
pub fn sequence() -> Vec<MigrationDescriptor> {
vec![
MigrationDescriptor {
version: i64::from(BASELINE_VERSION),
name: "community-baseline-v1",
checksum: BASELINE_CHECKSUM.to_owned(),
source_digest: BASELINE_SOURCE_SHA256.to_owned(),
phase: "expand",
compatibility: "legacy-baseline",
owner: "crank-registry",
transactional: true,
backfill: BackfillPolicy::None,
readable_schema_min: 1,
readable_schema_max: 1,
contract_evidence: None,
},
MigrationDescriptor {
version: 2,
name: "legacy-consolidation-v2",
checksum: CONSOLIDATION_SOURCE_SHA256.to_owned(),
source_digest: CONSOLIDATION_SOURCE_SHA256.to_owned(),
phase: "expand",
compatibility: "n-minus-one-readable",
owner: "crank-registry",
transactional: true,
backfill: BackfillPolicy::None,
readable_schema_min: 1,
readable_schema_max: 2,
contract_evidence: None,
},
MigrationDescriptor {
version: 3,
name: "request-trace-identity-v3",
checksum: REQUEST_TRACE_IDENTITY_SOURCE_SHA256.to_owned(),
source_digest: REQUEST_TRACE_IDENTITY_SOURCE_SHA256.to_owned(),
phase: "expand",
compatibility: "n-minus-one-readable",
owner: "crank-registry",
transactional: true,
backfill: BackfillPolicy::None,
readable_schema_min: 2,
readable_schema_max: 3,
contract_evidence: None,
},
]
}
pub fn validate_sequence() -> Result<(), MigrationError> {
validate_descriptors(&Self::sequence())
}
pub async fn preflight(pool: &PgPool) -> Result<MigrationPreflight, MigrationError> {
Self::validate_sequence()?;
let mut connection = pool
.acquire()
.await
.map_err(|_| MigrationError::storage("preflight.connect"))?;
inspect(&mut connection).await
}
pub async fn require_current(pool: &PgPool) -> Result<(), MigrationError> {
match Self::preflight(pool).await? {
MigrationPreflight::Current { .. } => Ok(()),
MigrationPreflight::MigrationRequired { current: 0, .. } => Err(MigrationError::new(
"schema_missing",
"preflight.compatibility",
Some(0),
"run_controlled_migration",
)),
MigrationPreflight::MigrationRequired { current, .. } => Err(MigrationError::new(
"migration_required",
"preflight.compatibility",
Some(current),
"run_controlled_migration",
)),
}
}
pub async fn apply(pool: &PgPool) -> Result<MigrationApplyResult, MigrationError> {
Self::validate_sequence()?;
let mut transaction = pool
.begin()
.await
.map_err(|_| MigrationError::storage("apply.begin"))?;
query("set local lock_timeout = '30s'")
.execute(&mut *transaction)
.await
.map_err(|_| MigrationError::storage("apply.lock_policy"))?;
query("select pg_advisory_xact_lock($1)")
.bind(MIGRATION_LOCK_ID)
.execute(&mut *transaction)
.await
.map_err(|error| {
if error
.as_database_error()
.and_then(|database| database.code())
.is_some_and(|code| matches!(code.as_ref(), "55P03" | "57014"))
{
MigrationError::new("lock_timeout", "apply.lock", None, "run_preflight")
} else {
MigrationError::storage("apply.lock")
}
})?;
let before = inspect(&mut transaction).await?;
let from = match before {
MigrationPreflight::Current { version } => {
transaction
.commit()
.await
.map_err(|_| MigrationError::storage("apply.commit"))?;
return Ok(MigrationApplyResult::AlreadyCurrent { version });
}
MigrationPreflight::MigrationRequired { current, .. } => current,
};
if from == 0 {
create_core_ledger(&mut transaction).await?;
apply_baseline(&mut transaction).await.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.baseline",
Some(1),
"restore_known_good_backup",
)
})?;
query(
"insert into __crank_core_migrations (version, description, checksum)
values (1, 'community baseline', $1)",
)
.bind(BASELINE_CHECKSUM)
.execute(&mut *transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.baseline_ledger",
Some(1),
"restore_known_good_backup",
)
})?;
}
if from < 2 {
apply_consolidation(&mut transaction).await?;
}
if from < 3 {
apply_request_trace_identity(&mut transaction).await?;
}
transaction
.commit()
.await
.map_err(|_| MigrationError::storage("apply.commit"))?;
Ok(MigrationApplyResult::Applied {
from,
to: CURRENT_VERSION,
})
}
}
fn sha256_hex(bytes: &[u8]) -> String {
format!("{:x}", Sha256::digest(bytes))
}
#[cfg(test)]
fn baseline_source_digest() -> String {
let source = include_str!("baseline_v1.rs");
let (_, baseline) = source
.split_once("// baseline-v1:start\n")
.expect("baseline start marker must exist");
let (baseline, _) = baseline
.split_once("// baseline-v1:end")
.expect("baseline end marker must exist");
sha256_hex(baseline.as_bytes())
}
fn validate_descriptors(descriptors: &[MigrationDescriptor]) -> Result<(), MigrationError> {
if descriptors.is_empty() || descriptors.len() > 1_024 {
return Err(MigrationError::new(
"invalid_contract",
"contract.sequence",
None,
"contact_operator",
));
}
for (index, descriptor) in descriptors.iter().enumerate() {
let expected_version = i64::try_from(index + 1).unwrap_or(i64::MAX);
let valid_name = !descriptor.name.is_empty()
&& descriptor.name.len() <= 128
&& descriptor
.name
.bytes()
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
&& !descriptors[..index]
.iter()
.any(|prior| prior.name == descriptor.name);
let valid_source_digest = descriptor.source_digest.len() == 64
&& descriptor
.source_digest
.bytes()
.all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase());
let valid_checksum = if descriptor.version == 1 {
descriptor.checksum == BASELINE_CHECKSUM
} else {
descriptor.checksum == descriptor.source_digest
};
let valid_window = descriptor.readable_schema_min >= 1
&& descriptor.readable_schema_min <= descriptor.readable_schema_max
&& descriptor.readable_schema_max <= descriptor.version;
let valid_phase = match descriptor.phase {
"expand" => descriptor.backfill == BackfillPolicy::None,
"migrate" => matches!(
descriptor.backfill,
BackfillPolicy::Bounded {
max_batch_rows: 1..=10_000,
max_batch_ms: 1..=60_000,
resumable: true,
}
),
"contract" => {
descriptor.compatibility == "window-closed"
&& descriptor.contract_evidence.is_some_and(|evidence| {
!evidence.is_empty()
&& evidence.len() <= 256
&& !evidence.starts_with('/')
&& !evidence.contains("..")
})
&& descriptor.backfill == BackfillPolicy::None
}
_ => false,
};
let valid_compatibility = matches!(
descriptor.compatibility,
"legacy-baseline" | "n-minus-one-readable" | "window-open" | "window-closed"
);
let valid_owner = !descriptor.owner.is_empty()
&& descriptor.owner.len() <= 128
&& descriptor
.owner
.bytes()
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-');
if descriptor.version != expected_version
|| !valid_name
|| !valid_source_digest
|| !valid_checksum
|| !valid_phase
|| !valid_compatibility
|| !valid_owner
|| !valid_window
|| !descriptor.transactional
{
return Err(MigrationError::new(
"invalid_contract",
"contract.sequence",
Some(descriptor.version),
"contact_operator",
));
}
}
if descriptors.len() != usize::try_from(CURRENT_VERSION).unwrap_or_default()
|| descriptors
.iter()
.map(|descriptor| descriptor.version)
.ne(IMPLEMENTED_VERSIONS.iter().copied())
|| sha256_hex(CONSOLIDATION_SOURCE.as_bytes()) != CONSOLIDATION_SOURCE_SHA256
|| sha256_hex(REQUEST_TRACE_IDENTITY_SOURCE.as_bytes())
!= REQUEST_TRACE_IDENTITY_SOURCE_SHA256
{
return Err(MigrationError::new(
"invalid_contract",
"contract.implementation",
Some(CURRENT_VERSION),
"contact_operator",
));
}
Ok(())
}
async fn inspect(connection: &mut PgConnection) -> Result<MigrationPreflight, MigrationError> {
let core_exists = relation_exists(connection, "__crank_core_migrations").await?;
let canonical_exists = relation_exists(connection, "__crank_migrations").await?;
if !core_exists {
let mut owned_exists = canonical_exists;
for relation in OWNED_RELATIONS {
owned_exists |= relation_exists(connection, relation).await?;
}
if owned_exists {
return Err(MigrationError::new(
"partial_sequence",
"preflight.core",
None,
"restore_known_good_backup",
));
}
inspect_optional_legacy(connection).await?;
return Ok(MigrationPreflight::MigrationRequired {
current: 0,
target: CURRENT_VERSION,
});
}
validate_core_ledger(connection).await?;
validate_required_relations(connection, BASELINE_RELATIONS, 1).await?;
inspect_optional_legacy(connection).await?;
if !canonical_exists {
return Ok(MigrationPreflight::MigrationRequired {
current: 1,
target: CURRENT_VERSION,
});
}
let descriptors = MigrationAuthority::sequence();
let rows = query("select version, name, checksum, phase, compatibility from __crank_migrations order by version limit 1025")
.fetch_all(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
if rows.is_empty() {
return Err(MigrationError::new(
"partial_sequence",
"preflight.canonical",
None,
"restore_known_good_backup",
));
}
for (index, row) in rows.iter().enumerate() {
let version = row
.try_get::<i64, _>("version")
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
if version > CURRENT_VERSION {
return Err(MigrationError::new(
"future_version",
"preflight.canonical",
Some(version),
"install_matching_application",
));
}
let Some(expected) = descriptors.get(index) else {
return Err(MigrationError::new(
"future_version",
"preflight.canonical",
Some(version),
"install_matching_application",
));
};
if version != expected.version {
return Err(MigrationError::new(
"partial_sequence",
"preflight.canonical",
Some(version),
"restore_known_good_backup",
));
}
let checksum = row
.try_get::<String, _>("checksum")
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
if checksum != expected.checksum {
return Err(MigrationError::new(
"checksum_mismatch",
"preflight.canonical",
Some(version),
"restore_known_good_backup",
));
}
let name = row
.try_get::<String, _>("name")
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
let phase = row
.try_get::<String, _>("phase")
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
let compatibility = row
.try_get::<String, _>("compatibility")
.map_err(|_| MigrationError::storage("preflight.canonical"))?;
if name != expected.name
|| phase != expected.phase
|| compatibility != expected.compatibility
{
return Err(MigrationError::new(
"checksum_mismatch",
"preflight.metadata",
Some(version),
"restore_known_good_backup",
));
}
}
let current = rows
.last()
.and_then(|row| row.try_get::<i64, _>("version").ok())
.ok_or_else(|| MigrationError::storage("preflight.canonical"))?;
if rows.len() != usize::try_from(current).unwrap_or_default() {
return Err(MigrationError::new(
"partial_sequence",
"preflight.canonical",
Some(current),
"restore_known_good_backup",
));
}
validate_schema_fingerprint(connection, current).await?;
if current < CURRENT_VERSION {
Ok(MigrationPreflight::MigrationRequired {
current,
target: CURRENT_VERSION,
})
} else {
validate_required_relations(connection, CONSOLIDATION_RELATIONS, CURRENT_VERSION).await?;
validate_schema_fingerprint(connection, CURRENT_VERSION).await?;
validate_legacy_audit(connection).await?;
Ok(MigrationPreflight::Current { version: current })
}
}
async fn validate_core_ledger(connection: &mut PgConnection) -> Result<(), MigrationError> {
let rows = query("select version, description, checksum from __crank_core_migrations order by version limit 2")
.fetch_all(connection)
.await
.map_err(|_| MigrationError::storage("preflight.core"))?;
if rows.len() != 1 {
return Err(MigrationError::new(
"partial_sequence",
"preflight.core",
None,
"restore_known_good_backup",
));
}
let version = rows[0]
.try_get::<i32, _>("version")
.map_err(|_| MigrationError::storage("preflight.core"))?;
let checksum = rows[0]
.try_get::<String, _>("checksum")
.map_err(|_| MigrationError::storage("preflight.core"))?;
let description = rows[0]
.try_get::<String, _>("description")
.map_err(|_| MigrationError::storage("preflight.core"))?;
if version != BASELINE_VERSION
|| description != "community baseline"
|| checksum != BASELINE_CHECKSUM
{
return Err(MigrationError::new(
"checksum_mismatch",
"preflight.core",
Some(i64::from(version)),
"restore_known_good_backup",
));
}
Ok(())
}
async fn inspect_optional_legacy(connection: &mut PgConnection) -> Result<(), MigrationError> {
let mcp_ledger = relation_exists(connection, "__crank_mcp_migrations").await?;
let mcp_sessions = relation_exists(connection, "mcp_transport_sessions").await?;
if mcp_ledger != mcp_sessions {
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_mcp",
None,
"restore_known_good_backup",
));
}
if mcp_ledger {
let rows =
query("select version, checksum from __crank_mcp_migrations order by version limit 2")
.fetch_all(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.legacy_mcp"))?;
if rows.len() != 1
|| rows[0].try_get::<i32, _>("version").ok() != Some(1)
|| rows[0].try_get::<String, _>("checksum").ok().as_deref()
!= Some("mcp-transport-sessions-v1")
{
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_mcp",
None,
"restore_known_good_backup",
));
}
}
if relation_exists(connection, "__crank_ext_migrations").await? {
let count = query("select count(*)::bigint as count from __crank_ext_migrations")
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?
.try_get::<i64, _>("count")
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
if count > 1_000 {
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_extension",
None,
"contact_operator",
));
}
if count > 0 {
let checksum_column = query(
"select exists (
select 1 from information_schema.columns
where table_schema = current_schema()
and table_name = '__crank_ext_migrations'
and column_name = 'checksum'
) as present",
)
.fetch_one(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?
.try_get::<bool, _>("present")
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
if !checksum_column {
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_extension",
None,
"contact_operator",
));
}
let rows = query(
"select extension_name, version, checksum
from __crank_ext_migrations
order by extension_name, version
limit 1001",
)
.fetch_all(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
for row in rows {
let name = row
.try_get::<String, _>("extension_name")
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
let version = row
.try_get::<i32, _>("version")
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
let checksum = row
.try_get::<Option<String>, _>("checksum")
.map_err(|_| MigrationError::storage("preflight.legacy_extension"))?;
let registered = MigrationAuthority::registered_extension_migrations()
.iter()
.any(|(registered_name, descriptor)| {
*registered_name == name
&& descriptor.version == u32::try_from(version).unwrap_or_default()
&& checksum.as_deref() == Some(descriptor.checksum)
});
if !registered {
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_extension",
Some(i64::from(version)),
"contact_operator",
));
}
}
}
}
Ok(())
}
async fn validate_legacy_audit(connection: &mut PgConnection) -> Result<(), MigrationError> {
let rows = query(
"select source, source_version, source_checksum
from __crank_migration_legacy_audit
order by source, source_version
limit 1002",
)
.fetch_all(&mut *connection)
.await
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
if rows.len() > 1001 {
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_audit",
None,
"contact_operator",
));
}
for row in rows {
let source = row
.try_get::<String, _>("source")
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
let version = row
.try_get::<i64, _>("source_version")
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
let checksum = row
.try_get::<String, _>("source_checksum")
.map_err(|_| MigrationError::storage("preflight.legacy_audit"))?;
let valid = (source == "core" && version == 1 && checksum == BASELINE_CHECKSUM)
|| (source == "mcp-session" && version == 1 && checksum == "mcp-transport-sessions-v1")
|| source.strip_prefix("extension:").is_some_and(|name| {
MigrationAuthority::registered_extension_migrations()
.iter()
.any(|(registered_name, descriptor)| {
*registered_name == name
&& i64::from(descriptor.version) == version
&& descriptor.checksum == checksum
})
});
if !valid {
return Err(MigrationError::new(
"legacy_conflict",
"preflight.legacy_audit",
Some(version),
"restore_known_good_backup",
));
}
}
Ok(())
}
async fn create_core_ledger(
transaction: &mut Transaction<'_, sqlx::Postgres>,
) -> Result<(), MigrationError> {
query(
"create table __crank_core_migrations (
version integer primary key,
description text not null,
checksum text not null,
applied_at timestamptz not null default now()
)",
)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.core_ledger",
Some(1),
"restore_known_good_backup",
)
})?;
Ok(())
}
async fn apply_consolidation(
transaction: &mut Transaction<'_, sqlx::Postgres>,
) -> Result<(), MigrationError> {
sqlx::raw_sql(CONSOLIDATION_SOURCE)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.consolidation",
Some(2),
"restore_known_good_backup",
)
})?;
for (name, extension) in MigrationAuthority::registered_extension_migrations() {
query(
"insert into __crank_migration_legacy_audit
(source, source_version, source_checksum)
select 'extension:' || $1, $2, $3
from __crank_ext_migrations
where extension_name = $1 and version = $2 and checksum = $3",
)
.bind(name)
.bind(i64::from(extension.version))
.bind(extension.checksum)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.extension_audit",
Some(2),
"restore_known_good_backup",
)
})?;
}
let descriptor = &MigrationAuthority::sequence()[1];
query(
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
values ($1, $2, $3, $4, $5)",
)
.bind(descriptor.version)
.bind(descriptor.name)
.bind(&descriptor.checksum)
.bind(descriptor.phase)
.bind(descriptor.compatibility)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.canonical_ledger",
Some(2),
"restore_known_good_backup",
)
})?;
Ok(())
}
async fn apply_request_trace_identity(
transaction: &mut Transaction<'_, sqlx::Postgres>,
) -> Result<(), MigrationError> {
sqlx::raw_sql(REQUEST_TRACE_IDENTITY_SOURCE)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.request_trace_identity",
Some(3),
"restore_known_good_backup",
)
})?;
let descriptor = &MigrationAuthority::sequence()[2];
query(
"insert into __crank_migrations (version, name, checksum, phase, compatibility)
values ($1, $2, $3, $4, $5)",
)
.bind(descriptor.version)
.bind(descriptor.name)
.bind(&descriptor.checksum)
.bind(descriptor.phase)
.bind(descriptor.compatibility)
.execute(&mut **transaction)
.await
.map_err(|_| {
MigrationError::new(
"apply_failed",
"apply.canonical_ledger",
Some(3),
"restore_known_good_backup",
)
})?;
Ok(())
}
#[cfg(test)]
#[path = "authority_tests.rs"]
mod tests;