feat: complete Epic 1 production foundation
This commit is contained in:
1 parent
767428436d
commit
182bde8ac0
298 files changed
+35711
-5291
No files matched your search
@@ -0,0 +1,603 @@
|
||||
use crank_core::product_event::PRODUCT_EVENT_SERVER_IDEMPOTENCY_PREFIX;
|
||||
use crank_core::{
|
||||
AgentId, InvocationLogId, OnboardingProjection, OnboardingStep, OnboardingStepId, OperationId,
|
||||
PRODUCT_EVENT_SCHEMA_VERSION, PlatformApiKeyId, ProductEvent, ProductEventKind,
|
||||
};
|
||||
use sqlx::Row;
|
||||
|
||||
use super::*;
|
||||
|
||||
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
|
||||
), 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,
|
||||
(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 (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'
|
||||
and l.execution_stage = 'runtime' and l.outcome_certainty = 'certain'
|
||||
and l.execution_error_code is null
|
||||
) as tested,
|
||||
exists (
|
||||
select 1 from published_operations po
|
||||
where po.operation_id = o.id
|
||||
and po.version = coalesce(ss.operation_version, 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 (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'
|
||||
and o.status <> 'archived'
|
||||
) as published_agent,
|
||||
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
|
||||
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 (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)
|
||||
and b.enabled and a.workspace_id = $1 and a.status = 'published'
|
||||
and o.status <> 'archived'
|
||||
and k.key_kind = 'mcp_client' and k.status = 'active'
|
||||
and (k.expires_at is null or k.expires_at > now())
|
||||
) as active_key,
|
||||
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
|
||||
join platform_api_keys k on k.workspace_id = $1 and k.agent_id = a.id
|
||||
join invocation_logs l
|
||||
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 (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)
|
||||
and b.enabled and a.workspace_id = $1 and a.status = 'published'
|
||||
and o.status <> 'archived'
|
||||
and k.key_kind = 'mcp_client' and k.status = 'active'
|
||||
and (k.expires_at is null or k.expires_at > now())
|
||||
and l.source = 'agent_tool_call' and l.status = 'ok'
|
||||
and l.execution_stage = 'runtime' and l.outcome_certainty = 'certain'
|
||||
and l.execution_error_code is null and l.created_at >= k.created_at
|
||||
and l.created_at >= pa.published_at
|
||||
and l.created_at >= coalesce(ss.evidence_after, '-infinity'::timestamptz)
|
||||
and (ss.invocation_log_id is null or l.id = ss.invocation_log_id)
|
||||
) as first_call_complete
|
||||
, 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
|
||||
join platform_api_keys k on k.workspace_id = $1 and k.agent_id = a.id
|
||||
join invocation_logs l
|
||||
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 (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)
|
||||
and b.enabled and a.workspace_id = $1
|
||||
and k.key_kind = 'mcp_client'
|
||||
and l.source = 'agent_tool_call' and l.status = 'ok'
|
||||
and l.execution_stage = 'runtime' and l.outcome_certainty = 'certain'
|
||||
and l.execution_error_code is null and l.created_at >= k.created_at
|
||||
and l.created_at >= pa.published_at
|
||||
and l.created_at >= coalesce(ss.evidence_after, '-infinity'::timestamptz)
|
||||
and (ss.invocation_log_id is null or l.id = ss.invocation_log_id)
|
||||
) 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)
|
||||
), selected_operation as (
|
||||
select o.id, o.current_draft_version, o.latest_published_version, o.updated_at, o.target_version,
|
||||
o.operation_active
|
||||
from operation_candidates o
|
||||
order by o.historical_first_call desc, o.operation_active desc,
|
||||
o.first_call_complete desc, o.active_key desc, o.published_agent desc,
|
||||
o.published desc, o.tested desc, o.updated_at desc, o.id
|
||||
limit 1
|
||||
), operation_state as (
|
||||
select so.*,
|
||||
(so.operation_active and exists (
|
||||
select 1 from invocation_logs l
|
||||
where l.workspace_id = $1 and l.operation_id = so.id
|
||||
and l.operation_version = so.target_version
|
||||
and l.created_at >= coalesce((select evidence_after from selection_state), '-infinity'::timestamptz)
|
||||
and ((select test_log_id from selection_state) is null
|
||||
or l.id = (select test_log_id from selection_state))
|
||||
and l.source = 'admin_test_run' and l.status = 'ok'
|
||||
and l.execution_stage = 'runtime' and l.outcome_certainty = 'certain'
|
||||
and l.execution_error_code is null
|
||||
)) as tested,
|
||||
(so.operation_active and so.current_draft_version = so.target_version
|
||||
and po.operation_id is not null and po.version = so.target_version) as published,
|
||||
po.version as published_version
|
||||
from selected_operation so
|
||||
left join published_operations po on po.operation_id = so.id and po.version = so.target_version
|
||||
), agent_candidates as (
|
||||
select a.id, pa.catalog_revision, pa.published_at as agent_published_at,
|
||||
a.updated_at, b.operation_id, b.operation_version, os.operation_active,
|
||||
(os.published and a.status = 'published') as agent_active,
|
||||
exists (
|
||||
select 1 from platform_api_keys k
|
||||
where k.workspace_id = $1 and k.agent_id = a.id
|
||||
and os.operation_active and a.status = 'published'
|
||||
and k.key_kind = 'mcp_client' and k.status = 'active'
|
||||
and (k.expires_at is null or k.expires_at > now())
|
||||
) as active_key,
|
||||
exists (
|
||||
select 1 from platform_api_keys k
|
||||
join invocation_logs l
|
||||
on l.workspace_id = $1 and l.agent_id = a.id and l.platform_api_key_id = k.id
|
||||
and l.operation_id = b.operation_id and l.operation_version = b.operation_version
|
||||
where k.workspace_id = $1 and k.agent_id = a.id
|
||||
and os.operation_active and a.status = 'published'
|
||||
and k.key_kind = 'mcp_client' and k.status = 'active'
|
||||
and (k.expires_at is null or k.expires_at > now())
|
||||
and l.source = 'agent_tool_call' and l.status = 'ok'
|
||||
and l.execution_stage = 'runtime' and l.outcome_certainty = 'certain'
|
||||
and l.execution_error_code is null and l.created_at >= k.created_at
|
||||
and l.created_at >= pa.published_at
|
||||
) as first_call_complete
|
||||
, exists (
|
||||
select 1 from platform_api_keys k
|
||||
join invocation_logs l
|
||||
on l.workspace_id = $1 and l.agent_id = a.id and l.platform_api_key_id = k.id
|
||||
and l.operation_id = b.operation_id and l.operation_version = b.operation_version
|
||||
where k.workspace_id = $1 and k.agent_id = a.id
|
||||
and k.key_kind = 'mcp_client'
|
||||
and l.source = 'agent_tool_call' and l.status = 'ok'
|
||||
and l.execution_stage = 'runtime' and l.outcome_certainty = 'certain'
|
||||
and l.execution_error_code is null and l.created_at >= k.created_at
|
||||
and l.created_at >= pa.published_at
|
||||
) as historical_first_call
|
||||
from operation_state os
|
||||
join agent_operation_bindings b
|
||||
on b.operation_id = os.id and b.operation_version = os.published_version and b.enabled
|
||||
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 a.workspace_id = $1
|
||||
and ((select agent_id from selection_state) is null
|
||||
or a.id = (select agent_id from selection_state))
|
||||
and ((select catalog_revision from selection_state) is null
|
||||
or pa.catalog_revision = (select catalog_revision from selection_state))
|
||||
), selected_agent as (
|
||||
select id, catalog_revision, agent_published_at, updated_at, operation_id, operation_version,
|
||||
operation_active, agent_active
|
||||
from agent_candidates
|
||||
order by historical_first_call desc, agent_active desc,
|
||||
first_call_complete desc, active_key desc, updated_at desc, id
|
||||
limit 1
|
||||
), key_candidates as (
|
||||
select k.id, k.agent_id, k.last_used_at, k.created_at, k.expires_at, k.status,
|
||||
(sa.agent_active and k.status = 'active'
|
||||
and (k.expires_at is null or k.expires_at > now())) as key_active,
|
||||
exists (
|
||||
select 1 from invocation_logs l
|
||||
where l.workspace_id = $1 and l.agent_id = sa.id and l.platform_api_key_id = k.id
|
||||
and l.operation_id = sa.operation_id and l.operation_version = sa.operation_version
|
||||
and l.source = 'agent_tool_call' and l.status = 'ok'
|
||||
and l.execution_stage = 'runtime' and l.outcome_certainty = 'certain'
|
||||
and l.execution_error_code is null and l.created_at >= k.created_at
|
||||
and l.created_at >= sa.agent_published_at
|
||||
) as first_call_complete
|
||||
from selected_agent sa
|
||||
join platform_api_keys k on k.workspace_id = $1 and k.agent_id = sa.id
|
||||
where k.key_kind = 'mcp_client'
|
||||
and ((select platform_api_key_id from selection_state) is null
|
||||
or k.id = (select platform_api_key_id from selection_state))
|
||||
), selected_key as (
|
||||
select id, agent_id, last_used_at, created_at, expires_at, status, key_active
|
||||
from key_candidates
|
||||
order by first_call_complete desc, key_active desc, (last_used_at is not null) desc, created_at desc, id
|
||||
limit 1
|
||||
), first_call as (
|
||||
select l.id, l.tool_name, l.created_at, l.request_id, l.trace_id
|
||||
from selected_agent sa
|
||||
join selected_key sk on sk.agent_id = sa.id
|
||||
join invocation_logs l
|
||||
on l.workspace_id = $1 and l.agent_id = sa.id and l.platform_api_key_id = sk.id
|
||||
and l.operation_id = sa.operation_id and l.operation_version = sa.operation_version
|
||||
where l.source = 'agent_tool_call' and l.status = 'ok'
|
||||
and sk.key_active
|
||||
and l.execution_stage = 'runtime' and l.outcome_certainty = 'certain'
|
||||
and l.execution_error_code is null
|
||||
and l.created_at >= sk.created_at
|
||||
and l.created_at >= sa.agent_published_at
|
||||
and l.created_at >= coalesce((select evidence_after from selection_state), '-infinity'::timestamptz)
|
||||
and ((select invocation_log_id from selection_state) is null
|
||||
or l.id = (select invocation_log_id from selection_state))
|
||||
order by l.created_at, l.id limit 1
|
||||
), event_state as (
|
||||
select count(*)::bigint as event_count, max(occurred_at) as last_event_at, max(id) as last_event_id,
|
||||
coalesce(bool_or(event_name = 'onboarding_completed'), false) as was_completed,
|
||||
min((properties_json ->> 'eligible_since')::timestamptz)
|
||||
filter (where event_name = 'onboarding_eligible') as eligible_since
|
||||
from product_events where workspace_id = $1
|
||||
)
|
||||
select os.id as operation_id, os.operation_active, os.tested, os.published, os.published_version,
|
||||
sa.id as agent_id, sa.agent_active, sa.catalog_revision, sk.id as platform_api_key_id,
|
||||
(sk.key_active and sk.last_used_at is not null) as connected, sk.key_active,
|
||||
fc.id as first_call_log_id, fc.tool_name as first_call_tool_name,
|
||||
fc.created_at as first_call_at, fc.request_id as first_call_request_id,
|
||||
fc.trace_id as first_call_trace_id, es.eligible_since, es.was_completed,
|
||||
(hashtextextended(concat_ws('|',
|
||||
coalesce(os.id, ''), coalesce(os.updated_at::text, ''), coalesce(os.tested::text, ''),
|
||||
coalesce(os.published_version::text, ''), coalesce(sa.id, ''),
|
||||
coalesce(sa.catalog_revision::text, ''), coalesce(sa.updated_at::text, ''),
|
||||
coalesce(sk.id, ''), coalesce(sk.status, ''), coalesce(sk.last_used_at::text, ''),
|
||||
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
|
||||
from event_state es
|
||||
left join operation_state os on true
|
||||
left join selected_agent sa on true
|
||||
left join selected_key sk on true
|
||||
left join first_call fc on true
|
||||
"#;
|
||||
|
||||
impl PostgresRegistry {
|
||||
/// 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(),
|
||||
occurred_at,
|
||||
};
|
||||
super::product_event::append_product_event_in_transaction(&mut transaction, &event)
|
||||
.await?;
|
||||
occurred_at
|
||||
};
|
||||
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?;
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
pub async fn get_onboarding_projection(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
) -> Result<OnboardingProjection, RegistryError> {
|
||||
let row = sqlx::query(ONBOARDING_PROJECTION_SQL)
|
||||
.bind(workspace_id.as_str())
|
||||
.fetch_one(&self.pool)
|
||||
.await?;
|
||||
map_projection(workspace_id, &row)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
pub async fn record_onboarding_milestone(
|
||||
&self,
|
||||
request: RecordOnboardingMilestoneRequest<'_>,
|
||||
) -> Result<OnboardingMilestoneResult, RegistryError> {
|
||||
let kind = match request.milestone {
|
||||
OnboardingPresentationMilestone::Eligible => ProductEventKind::OnboardingEligible,
|
||||
OnboardingPresentationMilestone::Started => ProductEventKind::OnboardingStarted,
|
||||
OnboardingPresentationMilestone::Resumed => ProductEventKind::OnboardingResumed,
|
||||
OnboardingPresentationMilestone::Dismissed => ProductEventKind::OnboardingDismissed,
|
||||
OnboardingPresentationMilestone::Abandoned => ProductEventKind::OnboardingAbandoned,
|
||||
};
|
||||
self.record_onboarding_event(
|
||||
request.workspace_id,
|
||||
request.event_id,
|
||||
kind,
|
||||
request.idempotency_key,
|
||||
request.expected_revision,
|
||||
request.occurred_at,
|
||||
request.eligible_since,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn record_onboarding_completion(
|
||||
&self,
|
||||
request: RecordOnboardingCompletionRequest<'_>,
|
||||
) -> Result<OnboardingMilestoneResult, RegistryError> {
|
||||
self.record_onboarding_event(
|
||||
request.workspace_id,
|
||||
request.event_id,
|
||||
ProductEventKind::OnboardingCompleted,
|
||||
request.idempotency_key,
|
||||
request.expected_revision,
|
||||
request.occurred_at,
|
||||
Some(request.eligible_since),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn record_onboarding_event(
|
||||
&self,
|
||||
workspace_id: &WorkspaceId,
|
||||
event_id: &ProductEventId,
|
||||
kind: ProductEventKind,
|
||||
idempotency_key: &str,
|
||||
expected_revision: i64,
|
||||
occurred_at: OffsetDateTime,
|
||||
eligible_since: Option<OffsetDateTime>,
|
||||
) -> Result<OnboardingMilestoneResult, 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,
|
||||
});
|
||||
}
|
||||
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?;
|
||||
transaction.commit().await?;
|
||||
Ok(OnboardingMilestoneResult {
|
||||
accepted: outcome == AppendProductEventOutcome::Recorded,
|
||||
projection,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async fn lock_onboarding_workspace(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
) -> Result<(), RegistryError> {
|
||||
let present = sqlx::query("select id from workspaces where id = $1 for update")
|
||||
.bind(workspace_id.as_str())
|
||||
.fetch_optional(&mut **transaction)
|
||||
.await?
|
||||
.is_some();
|
||||
if !present {
|
||||
return Err(RegistryError::WorkspaceNotFound {
|
||||
workspace_id: workspace_id.as_str().to_owned(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) async fn get_onboarding_projection_in_transaction(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
workspace_id: &WorkspaceId,
|
||||
) -> Result<OnboardingProjection, RegistryError> {
|
||||
let row = sqlx::query(ONBOARDING_PROJECTION_SQL)
|
||||
.bind(workspace_id.as_str())
|
||||
.fetch_one(&mut **transaction)
|
||||
.await?;
|
||||
map_projection(workspace_id, &row)
|
||||
}
|
||||
|
||||
fn map_projection(
|
||||
workspace_id: &WorkspaceId,
|
||||
row: &sqlx::postgres::PgRow,
|
||||
) -> Result<OnboardingProjection, RegistryError> {
|
||||
let operation_id = row
|
||||
.try_get::<Option<String>, _>("operation_id")?
|
||||
.map(OperationId::new);
|
||||
let operation_active = row
|
||||
.try_get::<Option<bool>, _>("operation_active")?
|
||||
.unwrap_or(false);
|
||||
let tested = row.try_get::<Option<bool>, _>("tested")?.unwrap_or(false);
|
||||
let published = row
|
||||
.try_get::<Option<bool>, _>("published")?
|
||||
.unwrap_or(false);
|
||||
let agent_id = row
|
||||
.try_get::<Option<String>, _>("agent_id")?
|
||||
.map(AgentId::new);
|
||||
let agent_active = row
|
||||
.try_get::<Option<bool>, _>("agent_active")?
|
||||
.unwrap_or(false);
|
||||
let key_id = row
|
||||
.try_get::<Option<String>, _>("platform_api_key_id")?
|
||||
.map(PlatformApiKeyId::new);
|
||||
let key_active = row
|
||||
.try_get::<Option<bool>, _>("key_active")?
|
||||
.unwrap_or(false);
|
||||
let connected = row
|
||||
.try_get::<Option<bool>, _>("connected")?
|
||||
.unwrap_or(false);
|
||||
let first_call_log_id = row
|
||||
.try_get::<Option<String>, _>("first_call_log_id")?
|
||||
.map(InvocationLogId::new);
|
||||
let flags = [
|
||||
operation_id.is_some() && operation_active,
|
||||
tested,
|
||||
published,
|
||||
agent_id.is_some() && agent_active,
|
||||
key_id.is_some() && key_active,
|
||||
connected,
|
||||
first_call_log_id.is_some(),
|
||||
];
|
||||
Ok(OnboardingProjection {
|
||||
workspace_id: workspace_id.clone(),
|
||||
revision: row.try_get("revision")?,
|
||||
completed: flags.into_iter().all(|flag| flag),
|
||||
was_completed: row.try_get("was_completed")?,
|
||||
steps: OnboardingStepId::ORDERED
|
||||
.into_iter()
|
||||
.zip(flags)
|
||||
.map(|(id, completed)| OnboardingStep { id, completed })
|
||||
.collect(),
|
||||
operation_id,
|
||||
operation_version: row
|
||||
.try_get::<Option<i32>, _>("published_version")?
|
||||
.map(|value| {
|
||||
u32::try_from(value).map_err(|_| RegistryError::InvalidNumericValue {
|
||||
field: "onboarding.operation_version",
|
||||
value: i64::from(value),
|
||||
})
|
||||
})
|
||||
.transpose()?,
|
||||
agent_id,
|
||||
catalog_revision: row.try_get("catalog_revision")?,
|
||||
platform_api_key_id: key_id,
|
||||
first_call_log_id,
|
||||
first_call_tool_name: row.try_get("first_call_tool_name")?,
|
||||
first_call_at: row.try_get("first_call_at")?,
|
||||
first_call_request_id: row.try_get("first_call_request_id")?,
|
||||
first_call_trace_id: row.try_get("first_call_trace_id")?,
|
||||
eligible_since: row.try_get("eligible_since")?,
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user