feat(import): complete OpenAPI onboarding and verify delivery
This commit is contained in:
1 parent
bb3e376767
commit
e93de7015a
244 files changed
+57020
-5139
No files matched your search
@@ -7,20 +7,58 @@ use sqlx::Row;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Bounded whole-transaction retries for transient PostgreSQL serialization
|
||||
/// failures. A `REPEATABLE READ` transaction that reads a row later updated by
|
||||
/// a concurrent transaction aborts with SQLSTATE `40001`; retrying from the
|
||||
/// start re-reads a consistent snapshot instead of continuing a partial,
|
||||
/// aborted transaction.
|
||||
const MAX_ONBOARDING_SERIALIZATION_ATTEMPTS: usize = 4;
|
||||
|
||||
/// Whether a registry error is a transient PostgreSQL serialization/deadlock
|
||||
/// failure that must abort and retry the whole transaction.
|
||||
pub(super) fn is_onboarding_serialization_failure(error: &RegistryError) -> bool {
|
||||
matches!(
|
||||
error,
|
||||
RegistryError::Storage(sqlx::Error::Database(database))
|
||||
if matches!(database.code().as_deref(), Some("40001") | Some("40P01"))
|
||||
)
|
||||
}
|
||||
|
||||
/// Begins an onboarding transaction with a true, consistent snapshot.
|
||||
///
|
||||
/// The onboarding projection aggregates many relations and is paired with a
|
||||
/// separately-read durable import context; the default `READ COMMITTED` would
|
||||
/// let each statement see a different snapshot and pair a revision with newer
|
||||
/// choices. `REPEATABLE READ` fixes one snapshot for the whole transaction.
|
||||
pub(super) async fn begin_onboarding_transaction<'a>(
|
||||
pool: &'a sqlx::PgPool,
|
||||
) -> Result<Transaction<'a, Postgres>, RegistryError> {
|
||||
let mut transaction = pool.begin().await?;
|
||||
sqlx::query("set transaction isolation level repeatable read")
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
Ok(transaction)
|
||||
}
|
||||
|
||||
const ONBOARDING_PROJECTION_SQL: &str = r#"
|
||||
with selection_state as (
|
||||
select operation_id, operation_version, agent_id, catalog_revision,
|
||||
platform_api_key_id, invocation_log_id, test_log_id, evidence_after, selected_at
|
||||
from onboarding_selections
|
||||
where workspace_id = $1
|
||||
), import_selection as (
|
||||
select application_idempotency_key, plan_digest, selected_operation_id,
|
||||
selected_operation_version, registered_at, selected_at
|
||||
from onboarding_import_selections
|
||||
where workspace_id = $1
|
||||
), operation_candidates as (
|
||||
select o.id, o.current_draft_version, o.latest_published_version, o.updated_at,
|
||||
coalesce(ss.operation_version, o.latest_published_version, o.current_draft_version) as target_version,
|
||||
coalesce(ss.operation_version, case when imp.selected_operation_id = o.id then imp.selected_operation_version end, o.latest_published_version, o.current_draft_version) as target_version,
|
||||
(o.status <> 'archived') as operation_active,
|
||||
exists (
|
||||
select 1 from invocation_logs l
|
||||
where l.workspace_id = $1 and l.operation_id = o.id
|
||||
and l.operation_version = coalesce(ss.operation_version, o.latest_published_version, o.current_draft_version)
|
||||
and l.operation_version = coalesce(ss.operation_version, case when imp.selected_operation_id = o.id then imp.selected_operation_version end, o.latest_published_version, o.current_draft_version)
|
||||
and (ss.test_log_id is null or l.id = ss.test_log_id)
|
||||
and l.created_at >= coalesce(ss.evidence_after, '-infinity'::timestamptz)
|
||||
and l.source = 'admin_test_run' and l.status = 'ok'
|
||||
@@ -30,14 +68,14 @@ with selection_state as (
|
||||
exists (
|
||||
select 1 from published_operations po
|
||||
where po.operation_id = o.id
|
||||
and po.version = coalesce(ss.operation_version, o.latest_published_version)
|
||||
and po.version = coalesce(ss.operation_version, case when imp.selected_operation_id = o.id then imp.selected_operation_version end, o.latest_published_version)
|
||||
) as published,
|
||||
exists (
|
||||
select 1 from agent_operation_bindings b
|
||||
join published_agents pa on pa.agent_id = b.agent_id and pa.version = b.agent_version
|
||||
join agents a on a.id = pa.agent_id
|
||||
where b.operation_id = o.id
|
||||
and b.operation_version = coalesce(ss.operation_version, o.latest_published_version)
|
||||
and b.operation_version = coalesce(ss.operation_version, case when imp.selected_operation_id = o.id then imp.selected_operation_version end, o.latest_published_version)
|
||||
and (ss.agent_id is null or a.id = ss.agent_id)
|
||||
and (ss.catalog_revision is null or pa.catalog_revision = ss.catalog_revision)
|
||||
and b.enabled and a.workspace_id = $1 and a.status = 'published'
|
||||
@@ -49,7 +87,7 @@ with selection_state as (
|
||||
join agents a on a.id = pa.agent_id
|
||||
join platform_api_keys k on k.workspace_id = $1 and k.agent_id = a.id
|
||||
where b.operation_id = o.id
|
||||
and b.operation_version = coalesce(ss.operation_version, o.latest_published_version)
|
||||
and b.operation_version = coalesce(ss.operation_version, case when imp.selected_operation_id = o.id then imp.selected_operation_version end, o.latest_published_version)
|
||||
and (ss.agent_id is null or a.id = ss.agent_id)
|
||||
and (ss.catalog_revision is null or pa.catalog_revision = ss.catalog_revision)
|
||||
and (ss.platform_api_key_id is null or k.id = ss.platform_api_key_id)
|
||||
@@ -67,7 +105,7 @@ with selection_state as (
|
||||
on l.workspace_id = $1 and l.agent_id = a.id and l.platform_api_key_id = k.id
|
||||
and l.operation_id = o.id and l.operation_version = b.operation_version
|
||||
where b.operation_id = o.id
|
||||
and b.operation_version = coalesce(ss.operation_version, o.latest_published_version)
|
||||
and b.operation_version = coalesce(ss.operation_version, case when imp.selected_operation_id = o.id then imp.selected_operation_version end, o.latest_published_version)
|
||||
and (ss.agent_id is null or a.id = ss.agent_id)
|
||||
and (ss.catalog_revision is null or pa.catalog_revision = ss.catalog_revision)
|
||||
and (ss.platform_api_key_id is null or k.id = ss.platform_api_key_id)
|
||||
@@ -91,7 +129,7 @@ with selection_state as (
|
||||
on l.workspace_id = $1 and l.agent_id = a.id and l.platform_api_key_id = k.id
|
||||
and l.operation_id = o.id and l.operation_version = b.operation_version
|
||||
where b.operation_id = o.id
|
||||
and b.operation_version = coalesce(ss.operation_version, o.latest_published_version)
|
||||
and b.operation_version = coalesce(ss.operation_version, case when imp.selected_operation_id = o.id then imp.selected_operation_version end, o.latest_published_version)
|
||||
and (ss.agent_id is null or a.id = ss.agent_id)
|
||||
and (ss.catalog_revision is null or pa.catalog_revision = ss.catalog_revision)
|
||||
and (ss.platform_api_key_id is null or k.id = ss.platform_api_key_id)
|
||||
@@ -106,7 +144,14 @@ with selection_state as (
|
||||
) as historical_first_call
|
||||
from operations o
|
||||
left join selection_state ss on true
|
||||
where o.workspace_id = $1 and (ss.operation_id is null or o.id = ss.operation_id)
|
||||
left join import_selection imp on true
|
||||
where o.workspace_id = $1
|
||||
and (ss.operation_id is null or o.id = ss.operation_id)
|
||||
and (
|
||||
ss.operation_id is not null
|
||||
or (imp.selected_operation_id is not null and o.id = imp.selected_operation_id)
|
||||
or (imp.selected_operation_id is null and not exists (select 1 from import_selection))
|
||||
)
|
||||
), selected_operation as (
|
||||
select o.id, o.current_draft_version, o.latest_published_version, o.updated_at, o.target_version,
|
||||
o.operation_active
|
||||
@@ -248,9 +293,39 @@ select os.id as operation_id, os.operation_active, os.tested, os.published, os.p
|
||||
coalesce(sk.expires_at::text, ''), coalesce(sk.key_active::text, ''),
|
||||
coalesce(fc.id, ''), coalesce(es.event_count::text, ''),
|
||||
coalesce(es.last_event_at::text, ''), coalesce(es.last_event_id, ''),
|
||||
coalesce((select evidence_after::text from selection_state), ''),
|
||||
coalesce((select selected_at::text from selection_state), '')
|
||||
), 0) & 9223372036854775807) as revision
|
||||
coalesce((select evidence_after::text from selection_state), ''),
|
||||
coalesce((select selected_at::text from selection_state), ''),
|
||||
coalesce((select application_idempotency_key from import_selection), ''),
|
||||
coalesce((select plan_digest from import_selection), ''),
|
||||
coalesce((select selected_operation_id from import_selection), ''),
|
||||
coalesce((select selected_operation_version::text from import_selection), ''),
|
||||
coalesce((select registered_at::text from import_selection), ''),
|
||||
coalesce((select selected_at::text from import_selection), ''),
|
||||
coalesce((select o.current_draft_version::text from operations o
|
||||
where o.workspace_id = $1
|
||||
and o.id = (select selected_operation_id from import_selection)), ''),
|
||||
coalesce((
|
||||
select string_agg(
|
||||
candidate.operation_id || ':' || coalesce(o.status, 'missing') || ':' ||
|
||||
coalesce(o.current_draft_version::text, 'null'),
|
||||
',' order by candidate.operation_id
|
||||
)
|
||||
from (
|
||||
select distinct outcome ->> 'operation_id' as operation_id
|
||||
from import_plan_applications a
|
||||
cross join lateral jsonb_array_elements(a.report -> 'outcomes') as outcome
|
||||
where a.workspace_id = $1
|
||||
and a.idempotency_key = (
|
||||
select application_idempotency_key from import_selection
|
||||
)
|
||||
and a.plan_digest = (select plan_digest from import_selection)
|
||||
and outcome ->> 'outcome' in ('created', 'versioned', 'renamed')
|
||||
and outcome ->> 'operation_id' is not null
|
||||
) candidate
|
||||
left join operations o
|
||||
on o.workspace_id = $1 and o.id = candidate.operation_id
|
||||
), '')
|
||||
), 0) & 9007199254740991) as revision
|
||||
from event_state es
|
||||
left join operation_state os on true
|
||||
left join selected_agent sa on true
|
||||
@@ -259,41 +334,120 @@ select os.id as operation_id, os.operation_active, os.tested, os.published, os.p
|
||||
"#;
|
||||
|
||||
impl PostgresRegistry {
|
||||
/// Retries a whole onboarding transaction on transient serialization
|
||||
/// failures. Each attempt starts from scratch, so an aborted transaction is
|
||||
/// never continued partially. Exhausted retries surface as a truthful
|
||||
/// revision conflict so the client reloads and revalidates.
|
||||
pub(super) async fn with_onboarding_retry<T, F, Fut>(
|
||||
&self,
|
||||
mut operation: F,
|
||||
) -> Result<T, RegistryError>
|
||||
where
|
||||
F: FnMut() -> Fut,
|
||||
Fut: std::future::Future<Output = Result<T, RegistryError>>,
|
||||
{
|
||||
let mut attempt = 0;
|
||||
loop {
|
||||
match operation().await {
|
||||
Err(error) if is_onboarding_serialization_failure(&error) => {
|
||||
attempt += 1;
|
||||
if attempt >= MAX_ONBOARDING_SERIALIZATION_ATTEMPTS {
|
||||
return Err(RegistryError::OnboardingStaleRevision);
|
||||
}
|
||||
}
|
||||
result => return result,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Ensures the workspace enters the server-owned onboarding cohort exactly once.
|
||||
pub async fn ensure_onboarding_eligibility(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
occurred_at: OffsetDateTime,
|
||||
) -> Result<OnboardingProjection, RegistryError> {
|
||||
let mut transaction = self.pool.begin().await?;
|
||||
lock_onboarding_workspace(&mut transaction, workspace_id).await?;
|
||||
let eligible = super::product_event::get_product_event_by_idempotency_key_in_transaction(
|
||||
&mut transaction,
|
||||
workspace_id,
|
||||
"onboarding:eligible:v1",
|
||||
)
|
||||
.await?;
|
||||
let eligible_since = if let Some(record) = eligible {
|
||||
record.event.eligible_since.unwrap_or(occurred_at)
|
||||
} else {
|
||||
let event = ProductEvent {
|
||||
id: ProductEventId::new(format!("pe_{}", uuid::Uuid::now_v7().simple())),
|
||||
workspace_id: workspace_id.clone(),
|
||||
kind: ProductEventKind::OnboardingEligible,
|
||||
schema_version: PRODUCT_EVENT_SCHEMA_VERSION,
|
||||
milestone: None,
|
||||
eligible: true,
|
||||
eligible_since: Some(occurred_at),
|
||||
idempotency_key: "onboarding:eligible:v1".to_owned(),
|
||||
Ok(self
|
||||
.ensure_onboarding_eligibility_snapshot(workspace_id, occurred_at)
|
||||
.await?
|
||||
.projection)
|
||||
}
|
||||
|
||||
/// Ensures eligibility and returns the authoritative projection together
|
||||
/// with the durable import context from the same locked transaction.
|
||||
pub async fn ensure_onboarding_eligibility_snapshot(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
occurred_at: OffsetDateTime,
|
||||
) -> Result<OnboardingSnapshot, RegistryError> {
|
||||
self.with_onboarding_retry(|| async {
|
||||
let mut transaction = begin_onboarding_transaction(&self.pool).await?;
|
||||
lock_onboarding_workspace(&mut transaction, workspace_id).await?;
|
||||
let eligible_since = ensure_onboarding_eligible_in_transaction(
|
||||
&mut transaction,
|
||||
workspace_id,
|
||||
occurred_at,
|
||||
};
|
||||
super::product_event::append_product_event_in_transaction(&mut transaction, &event)
|
||||
)
|
||||
.await?;
|
||||
super::onboarding_import::record_import_funnel_milestones_in_transaction(
|
||||
&mut transaction,
|
||||
workspace_id,
|
||||
occurred_at,
|
||||
)
|
||||
.await?;
|
||||
let mut projection =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?;
|
||||
if projection.completed && !projection.was_completed {
|
||||
let event = ProductEvent {
|
||||
id: ProductEventId::new(format!("pe_{}", uuid::Uuid::now_v7().simple())),
|
||||
workspace_id: workspace_id.clone(),
|
||||
kind: ProductEventKind::OnboardingCompleted,
|
||||
schema_version: PRODUCT_EVENT_SCHEMA_VERSION,
|
||||
milestone: None,
|
||||
eligible: true,
|
||||
eligible_since: Some(eligible_since),
|
||||
idempotency_key: "onboarding:completed:v1".to_owned(),
|
||||
occurred_at: projection.first_call_at.unwrap_or(occurred_at),
|
||||
};
|
||||
super::product_event::append_product_event_in_transaction(&mut transaction, &event)
|
||||
.await?;
|
||||
projection =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, workspace_id)
|
||||
.await?;
|
||||
}
|
||||
let import_context =
|
||||
super::onboarding_import::get_onboarding_import_context_in_transaction(
|
||||
&mut transaction,
|
||||
workspace_id,
|
||||
)
|
||||
.await?;
|
||||
occurred_at
|
||||
};
|
||||
let mut projection =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?;
|
||||
if projection.completed && !projection.was_completed {
|
||||
transaction.commit().await?;
|
||||
Ok(OnboardingSnapshot {
|
||||
projection,
|
||||
import_context,
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Records the server-owned completion once the authoritative projection is terminal.
|
||||
pub async fn ensure_onboarding_completion(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
_occurred_at: OffsetDateTime,
|
||||
) -> Result<OnboardingProjection, RegistryError> {
|
||||
self.with_onboarding_retry(|| async {
|
||||
let mut transaction = begin_onboarding_transaction(&self.pool).await?;
|
||||
lock_onboarding_workspace(&mut transaction, workspace_id).await?;
|
||||
let projection =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?;
|
||||
if !projection.completed {
|
||||
transaction.commit().await?;
|
||||
return Ok(projection);
|
||||
}
|
||||
let Some(eligible_since) = projection.eligible_since else {
|
||||
transaction.commit().await?;
|
||||
return Ok(projection);
|
||||
};
|
||||
let event = ProductEvent {
|
||||
id: ProductEventId::new(format!("pe_{}", uuid::Uuid::now_v7().simple())),
|
||||
workspace_id: workspace_id.clone(),
|
||||
@@ -303,55 +457,20 @@ impl PostgresRegistry {
|
||||
eligible: true,
|
||||
eligible_since: Some(eligible_since),
|
||||
idempotency_key: "onboarding:completed:v1".to_owned(),
|
||||
occurred_at: projection.first_call_at.unwrap_or(occurred_at),
|
||||
occurred_at: projection.first_call_at.ok_or(
|
||||
RegistryError::InvalidExecutionRecord {
|
||||
field: "onboarding.first_call_at",
|
||||
},
|
||||
)?,
|
||||
};
|
||||
super::product_event::append_product_event_in_transaction(&mut transaction, &event)
|
||||
.await?;
|
||||
projection =
|
||||
let projection =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?;
|
||||
}
|
||||
transaction.commit().await?;
|
||||
Ok(projection)
|
||||
}
|
||||
|
||||
/// Records the server-owned completion once the authoritative projection is terminal.
|
||||
pub async fn ensure_onboarding_completion(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
_occurred_at: OffsetDateTime,
|
||||
) -> Result<OnboardingProjection, RegistryError> {
|
||||
let mut transaction = self.pool.begin().await?;
|
||||
lock_onboarding_workspace(&mut transaction, workspace_id).await?;
|
||||
let projection =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?;
|
||||
if !projection.completed {
|
||||
transaction.commit().await?;
|
||||
return Ok(projection);
|
||||
}
|
||||
let Some(eligible_since) = projection.eligible_since else {
|
||||
transaction.commit().await?;
|
||||
return Ok(projection);
|
||||
};
|
||||
let event = ProductEvent {
|
||||
id: ProductEventId::new(format!("pe_{}", uuid::Uuid::now_v7().simple())),
|
||||
workspace_id: workspace_id.clone(),
|
||||
kind: ProductEventKind::OnboardingCompleted,
|
||||
schema_version: PRODUCT_EVENT_SCHEMA_VERSION,
|
||||
milestone: None,
|
||||
eligible: true,
|
||||
eligible_since: Some(eligible_since),
|
||||
idempotency_key: "onboarding:completed:v1".to_owned(),
|
||||
occurred_at: projection
|
||||
.first_call_at
|
||||
.ok_or(RegistryError::InvalidExecutionRecord {
|
||||
field: "onboarding.first_call_at",
|
||||
})?,
|
||||
};
|
||||
super::product_event::append_product_event_in_transaction(&mut transaction, &event).await?;
|
||||
let projection =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?;
|
||||
transaction.commit().await?;
|
||||
Ok(projection)
|
||||
Ok(projection)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn get_onboarding_projection(
|
||||
@@ -365,44 +484,107 @@ impl PostgresRegistry {
|
||||
map_projection(workspace_id, &row)
|
||||
}
|
||||
|
||||
/// Reads the authoritative projection and the durable import context from
|
||||
/// one workspace-locked transaction so revision and context cannot diverge.
|
||||
pub async fn get_onboarding_snapshot(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
) -> Result<OnboardingSnapshot, RegistryError> {
|
||||
self.with_onboarding_retry(|| async {
|
||||
let mut transaction = begin_onboarding_transaction(&self.pool).await?;
|
||||
lock_onboarding_workspace(&mut transaction, workspace_id).await?;
|
||||
let snapshot =
|
||||
get_onboarding_snapshot_in_transaction(&mut transaction, workspace_id).await?;
|
||||
transaction.commit().await?;
|
||||
Ok(snapshot)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn reset_onboarding_selection(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
expected_revision: i64,
|
||||
occurred_at: OffsetDateTime,
|
||||
) -> Result<OnboardingProjection, RegistryError> {
|
||||
let mut transaction = self.pool.begin().await?;
|
||||
lock_onboarding_workspace(&mut transaction, workspace_id).await?;
|
||||
let current =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?;
|
||||
if current.revision != expected_revision {
|
||||
return Err(RegistryError::OnboardingStaleRevision);
|
||||
}
|
||||
sqlx::query(
|
||||
"insert into onboarding_selections (
|
||||
workspace_id, operation_id, operation_version, agent_id, catalog_revision,
|
||||
platform_api_key_id, invocation_log_id, test_log_id, evidence_after, selected_at
|
||||
) values ($1, null, null, null, null, null, null, null, $2, null)
|
||||
on conflict (workspace_id) do update
|
||||
set operation_id = null, operation_version = null, agent_id = null,
|
||||
catalog_revision = null, platform_api_key_id = null,
|
||||
invocation_log_id = null, test_log_id = null,
|
||||
evidence_after = excluded.evidence_after, selected_at = null",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(occurred_at)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
let projection =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?;
|
||||
transaction.commit().await?;
|
||||
Ok(projection)
|
||||
Ok(self
|
||||
.reset_onboarding_selection_snapshot(workspace_id, expected_revision, occurred_at)
|
||||
.await?
|
||||
.projection)
|
||||
}
|
||||
|
||||
/// Resets the terminal/import selection and returns the resulting
|
||||
/// projection with its (now absent) import context from one snapshot.
|
||||
pub async fn reset_onboarding_selection_snapshot(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
expected_revision: i64,
|
||||
occurred_at: OffsetDateTime,
|
||||
) -> Result<OnboardingSnapshot, RegistryError> {
|
||||
self.with_onboarding_retry(|| async {
|
||||
let mut transaction = begin_onboarding_transaction(&self.pool).await?;
|
||||
lock_onboarding_workspace(&mut transaction, workspace_id).await?;
|
||||
let current =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?;
|
||||
if current.revision != expected_revision {
|
||||
return Err(RegistryError::OnboardingStaleRevision);
|
||||
}
|
||||
sqlx::query(
|
||||
"insert into onboarding_selections (
|
||||
workspace_id, operation_id, operation_version, agent_id, catalog_revision,
|
||||
platform_api_key_id, invocation_log_id, test_log_id, evidence_after, selected_at
|
||||
) values ($1, null, null, null, null, null, null, null, $2, null)
|
||||
on conflict (workspace_id) do update
|
||||
set operation_id = null, operation_version = null, agent_id = null,
|
||||
catalog_revision = null, platform_api_key_id = null,
|
||||
invocation_log_id = null, test_log_id = null,
|
||||
evidence_after = excluded.evidence_after, selected_at = null",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(occurred_at)
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
// Reset clears the durable import context as well, but keeps the
|
||||
// existing evidence boundary (evidence_after) intact.
|
||||
sqlx::query("delete from onboarding_import_selections where workspace_id = $1")
|
||||
.bind(workspace_id.as_str())
|
||||
.execute(&mut *transaction)
|
||||
.await?;
|
||||
let projection =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?;
|
||||
let import_context =
|
||||
super::onboarding_import::get_onboarding_import_context_in_transaction(
|
||||
&mut transaction,
|
||||
workspace_id,
|
||||
)
|
||||
.await?;
|
||||
transaction.commit().await?;
|
||||
Ok(OnboardingSnapshot {
|
||||
projection,
|
||||
import_context,
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn record_onboarding_milestone(
|
||||
&self,
|
||||
request: RecordOnboardingMilestoneRequest<'_>,
|
||||
) -> Result<OnboardingMilestoneResult, RegistryError> {
|
||||
let snapshot = self.record_onboarding_milestone_snapshot(request).await?;
|
||||
Ok(OnboardingMilestoneResult {
|
||||
accepted: snapshot.accepted,
|
||||
projection: snapshot.snapshot.projection,
|
||||
})
|
||||
}
|
||||
|
||||
/// Records a presentation milestone and returns the projection and import
|
||||
/// context read from the same transaction, avoiding a post-mutation pool
|
||||
/// read that could pair the revision with a newer context.
|
||||
pub async fn record_onboarding_milestone_snapshot(
|
||||
&self,
|
||||
request: RecordOnboardingMilestoneRequest<'_>,
|
||||
) -> Result<OnboardingEventSnapshot, RegistryError> {
|
||||
let kind = match request.milestone {
|
||||
OnboardingPresentationMilestone::Eligible => ProductEventKind::OnboardingEligible,
|
||||
OnboardingPresentationMilestone::Started => ProductEventKind::OnboardingStarted,
|
||||
@@ -410,7 +592,7 @@ impl PostgresRegistry {
|
||||
OnboardingPresentationMilestone::Dismissed => ProductEventKind::OnboardingDismissed,
|
||||
OnboardingPresentationMilestone::Abandoned => ProductEventKind::OnboardingAbandoned,
|
||||
};
|
||||
self.record_onboarding_event(
|
||||
self.record_onboarding_event_snapshot(
|
||||
request.workspace_id,
|
||||
request.event_id,
|
||||
kind,
|
||||
@@ -426,7 +608,20 @@ impl PostgresRegistry {
|
||||
&self,
|
||||
request: RecordOnboardingCompletionRequest<'_>,
|
||||
) -> Result<OnboardingMilestoneResult, RegistryError> {
|
||||
self.record_onboarding_event(
|
||||
let snapshot = self.record_onboarding_completion_snapshot(request).await?;
|
||||
Ok(OnboardingMilestoneResult {
|
||||
accepted: snapshot.accepted,
|
||||
projection: snapshot.snapshot.projection,
|
||||
})
|
||||
}
|
||||
|
||||
/// Records the authoritative completion and returns the projection and
|
||||
/// import context from the same transaction.
|
||||
pub async fn record_onboarding_completion_snapshot(
|
||||
&self,
|
||||
request: RecordOnboardingCompletionRequest<'_>,
|
||||
) -> Result<OnboardingEventSnapshot, RegistryError> {
|
||||
self.record_onboarding_event_snapshot(
|
||||
request.workspace_id,
|
||||
request.event_id,
|
||||
ProductEventKind::OnboardingCompleted,
|
||||
@@ -439,7 +634,7 @@ impl PostgresRegistry {
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn record_onboarding_event(
|
||||
async fn record_onboarding_event_snapshot(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
event_id: &ProductEventId,
|
||||
@@ -448,60 +643,114 @@ impl PostgresRegistry {
|
||||
expected_revision: i64,
|
||||
occurred_at: OffsetDateTime,
|
||||
eligible_since: Option<OffsetDateTime>,
|
||||
) -> Result<OnboardingMilestoneResult, RegistryError> {
|
||||
) -> Result<OnboardingEventSnapshot, RegistryError> {
|
||||
if idempotency_key.starts_with(PRODUCT_EVENT_SERVER_IDEMPOTENCY_PREFIX) {
|
||||
return Err(RegistryError::InvalidExecutionRecord {
|
||||
field: "product_event.reserved_idempotency_key",
|
||||
});
|
||||
}
|
||||
let mut transaction = self.pool.begin().await?;
|
||||
lock_onboarding_workspace(&mut transaction, workspace_id).await?;
|
||||
let current =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?;
|
||||
if kind == ProductEventKind::OnboardingCompleted && !current.completed {
|
||||
return Err(RegistryError::OnboardingIncomplete);
|
||||
}
|
||||
let event = ProductEvent {
|
||||
id: event_id.clone(),
|
||||
workspace_id: workspace_id.clone(),
|
||||
kind,
|
||||
schema_version: PRODUCT_EVENT_SCHEMA_VERSION,
|
||||
milestone: None,
|
||||
eligible: eligible_since.is_some(),
|
||||
eligible_since,
|
||||
idempotency_key: idempotency_key.to_owned(),
|
||||
occurred_at,
|
||||
};
|
||||
if current.revision != expected_revision {
|
||||
let replay = super::product_event::get_product_event_by_idempotency_key_in_transaction(
|
||||
&mut transaction,
|
||||
workspace_id,
|
||||
idempotency_key,
|
||||
)
|
||||
.await?;
|
||||
if replay.is_some_and(|record| event.is_semantic_replay_of(&record.event)) {
|
||||
transaction.commit().await?;
|
||||
return Ok(OnboardingMilestoneResult {
|
||||
accepted: false,
|
||||
projection: current,
|
||||
});
|
||||
self.with_onboarding_retry(|| async {
|
||||
let mut transaction = begin_onboarding_transaction(&self.pool).await?;
|
||||
lock_onboarding_workspace(&mut transaction, workspace_id).await?;
|
||||
let current =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?;
|
||||
if kind == ProductEventKind::OnboardingCompleted && !current.completed {
|
||||
return Err(RegistryError::OnboardingIncomplete);
|
||||
}
|
||||
return Err(RegistryError::OnboardingStaleRevision);
|
||||
}
|
||||
let outcome =
|
||||
super::product_event::append_product_event_in_transaction(&mut transaction, &event)
|
||||
let event = ProductEvent {
|
||||
id: event_id.clone(),
|
||||
workspace_id: workspace_id.clone(),
|
||||
kind,
|
||||
schema_version: PRODUCT_EVENT_SCHEMA_VERSION,
|
||||
milestone: None,
|
||||
eligible: eligible_since.is_some(),
|
||||
eligible_since,
|
||||
idempotency_key: idempotency_key.to_owned(),
|
||||
occurred_at,
|
||||
};
|
||||
if current.revision != expected_revision {
|
||||
let replay =
|
||||
super::product_event::get_product_event_by_idempotency_key_in_transaction(
|
||||
&mut transaction,
|
||||
workspace_id,
|
||||
idempotency_key,
|
||||
)
|
||||
.await?;
|
||||
if replay.is_some_and(|record| event.is_semantic_replay_of(&record.event)) {
|
||||
let import_context =
|
||||
super::onboarding_import::get_onboarding_import_context_in_transaction(
|
||||
&mut transaction,
|
||||
workspace_id,
|
||||
)
|
||||
.await?;
|
||||
transaction.commit().await?;
|
||||
return Ok(OnboardingEventSnapshot {
|
||||
accepted: false,
|
||||
snapshot: OnboardingSnapshot {
|
||||
projection: current,
|
||||
import_context,
|
||||
},
|
||||
});
|
||||
}
|
||||
return Err(RegistryError::OnboardingStaleRevision);
|
||||
}
|
||||
let outcome =
|
||||
super::product_event::append_product_event_in_transaction(&mut transaction, &event)
|
||||
.await?;
|
||||
let projection =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?;
|
||||
let import_context =
|
||||
super::onboarding_import::get_onboarding_import_context_in_transaction(
|
||||
&mut transaction,
|
||||
workspace_id,
|
||||
)
|
||||
.await?;
|
||||
let projection =
|
||||
get_onboarding_projection_in_transaction(&mut transaction, workspace_id).await?;
|
||||
transaction.commit().await?;
|
||||
Ok(OnboardingMilestoneResult {
|
||||
accepted: outcome == AppendProductEventOutcome::Recorded,
|
||||
projection,
|
||||
transaction.commit().await?;
|
||||
Ok(OnboardingEventSnapshot {
|
||||
accepted: outcome == AppendProductEventOutcome::Recorded,
|
||||
snapshot: OnboardingSnapshot {
|
||||
projection,
|
||||
import_context,
|
||||
},
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
async fn lock_onboarding_workspace(
|
||||
/// Ensures the workspace is in the server-owned onboarding eligible cohort and
|
||||
/// returns its authoritative `eligible_since` timestamp. Idempotent: the
|
||||
/// cohort event is created at most once per workspace.
|
||||
pub(super) async fn ensure_onboarding_eligible_in_transaction(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
occurred_at: OffsetDateTime,
|
||||
) -> Result<OffsetDateTime, RegistryError> {
|
||||
let eligible = super::product_event::get_product_event_by_idempotency_key_in_transaction(
|
||||
transaction,
|
||||
workspace_id,
|
||||
"onboarding:eligible:v1",
|
||||
)
|
||||
.await?;
|
||||
if let Some(record) = eligible {
|
||||
return Ok(record.event.eligible_since.unwrap_or(occurred_at));
|
||||
}
|
||||
let event = ProductEvent {
|
||||
id: ProductEventId::new(format!("pe_{}", uuid::Uuid::now_v7().simple())),
|
||||
workspace_id: workspace_id.clone(),
|
||||
kind: ProductEventKind::OnboardingEligible,
|
||||
schema_version: PRODUCT_EVENT_SCHEMA_VERSION,
|
||||
milestone: None,
|
||||
eligible: true,
|
||||
eligible_since: Some(occurred_at),
|
||||
idempotency_key: "onboarding:eligible:v1".to_owned(),
|
||||
occurred_at,
|
||||
};
|
||||
super::product_event::append_product_event_in_transaction(transaction, &event).await?;
|
||||
Ok(occurred_at)
|
||||
}
|
||||
|
||||
pub(super) async fn lock_onboarding_workspace(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
) -> Result<(), RegistryError> {
|
||||
@@ -529,6 +778,22 @@ pub(super) async fn get_onboarding_projection_in_transaction(
|
||||
map_projection(workspace_id, &row)
|
||||
}
|
||||
|
||||
pub(super) async fn get_onboarding_snapshot_in_transaction(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
) -> Result<OnboardingSnapshot, RegistryError> {
|
||||
let projection = get_onboarding_projection_in_transaction(transaction, workspace_id).await?;
|
||||
let import_context = super::onboarding_import::get_onboarding_import_context_in_transaction(
|
||||
transaction,
|
||||
workspace_id,
|
||||
)
|
||||
.await?;
|
||||
Ok(OnboardingSnapshot {
|
||||
projection,
|
||||
import_context,
|
||||
})
|
||||
}
|
||||
|
||||
fn map_projection(
|
||||
workspace_id: &WorkspaceId,
|
||||
row: &sqlx::postgres::PgRow,
|
||||
|
||||
Reference in new issue
Block a user