407 lines
16 KiB
Rust
407 lines
16 KiB
Rust
use crank_core::{
|
|
OnboardingProjection, OnboardingStepId, OperationId, ProductEventId, ProductEventKind,
|
|
WorkspaceId,
|
|
};
|
|
use crank_registry::{
|
|
OnboardingImportContext, OnboardingPresentationMilestone, RecordOnboardingMilestoneRequest,
|
|
RegisterOnboardingImportContextRequest, RegistryError, SelectOnboardingImportDraftRequest,
|
|
};
|
|
use serde_json::json;
|
|
use time::OffsetDateTime;
|
|
|
|
use crate::{
|
|
error::ApiError,
|
|
service::{
|
|
AdminService, OnboardingEventPayload, OnboardingEventResponse, OnboardingFirstCallEvidence,
|
|
OnboardingImportChoiceView, OnboardingImportContextView, OnboardingImportDriftView,
|
|
OnboardingResponse, OnboardingStepView, RegisterOnboardingImportContextPayload,
|
|
RegisterOnboardingImportContextResponse, ResetOnboardingSelectionResponse,
|
|
SelectOnboardingImportDraftPayload, SelectOnboardingImportDraftResponse, format_timestamp,
|
|
new_prefixed_id,
|
|
},
|
|
};
|
|
|
|
impl AdminService {
|
|
pub async fn get_onboarding(
|
|
&self,
|
|
workspace_id: &WorkspaceId,
|
|
) -> Result<OnboardingResponse, ApiError> {
|
|
self.ensure_workspace_exists(workspace_id).await?;
|
|
let snapshot = self
|
|
.registry
|
|
.ensure_onboarding_eligibility_snapshot(workspace_id, OffsetDateTime::now_utc())
|
|
.await?;
|
|
self.map_onboarding_response(snapshot.projection, snapshot.import_context)
|
|
.await
|
|
}
|
|
|
|
pub async fn record_onboarding_event(
|
|
&self,
|
|
workspace_id: &WorkspaceId,
|
|
payload: OnboardingEventPayload,
|
|
) -> Result<OnboardingEventResponse, ApiError> {
|
|
self.ensure_workspace_exists(workspace_id).await?;
|
|
if payload.completed_steps.is_some() || payload.event == "completed" {
|
|
return Err(onboarding_event_not_allowed());
|
|
}
|
|
if payload.idempotency_key.is_empty() || payload.idempotency_key.len() > 256 {
|
|
return Err(ApiError::validation(
|
|
"idempotency_key must contain 1..256 bytes",
|
|
));
|
|
}
|
|
if payload.idempotency_key.starts_with("onboarding:") {
|
|
return Err(onboarding_event_not_allowed());
|
|
}
|
|
let (milestone, event_kind) = match payload.event.as_str() {
|
|
"started" => (
|
|
OnboardingPresentationMilestone::Started,
|
|
ProductEventKind::OnboardingStarted,
|
|
),
|
|
"resumed" => (
|
|
OnboardingPresentationMilestone::Resumed,
|
|
ProductEventKind::OnboardingResumed,
|
|
),
|
|
"dismissed" => (
|
|
OnboardingPresentationMilestone::Dismissed,
|
|
ProductEventKind::OnboardingDismissed,
|
|
),
|
|
"abandoned" => (
|
|
OnboardingPresentationMilestone::Abandoned,
|
|
ProductEventKind::OnboardingAbandoned,
|
|
),
|
|
_ => return Err(onboarding_event_not_allowed()),
|
|
};
|
|
// Presentation events must never exist outside the server-owned cohort,
|
|
// including a direct API call before the first UI snapshot GET.
|
|
self.registry
|
|
.ensure_onboarding_eligibility_snapshot(workspace_id, OffsetDateTime::now_utc())
|
|
.await?;
|
|
let outcome = self
|
|
.registry
|
|
.record_onboarding_milestone_snapshot(RecordOnboardingMilestoneRequest {
|
|
workspace_id,
|
|
event_id: &ProductEventId::new(new_prefixed_id("pe")),
|
|
milestone,
|
|
idempotency_key: &payload.idempotency_key,
|
|
expected_revision: payload.expected_revision,
|
|
occurred_at: OffsetDateTime::now_utc(),
|
|
eligible_since: None,
|
|
})
|
|
.await;
|
|
let outcome = match outcome {
|
|
Ok(outcome) => outcome,
|
|
Err(RegistryError::OnboardingStaleRevision) => {
|
|
let replay = self
|
|
.registry
|
|
.get_product_event_by_idempotency_key(workspace_id, &payload.idempotency_key)
|
|
.await?;
|
|
if replay
|
|
.as_ref()
|
|
.is_some_and(|record| record.event.kind == event_kind)
|
|
{
|
|
let latest = self
|
|
.registry
|
|
.ensure_onboarding_eligibility_snapshot(
|
|
workspace_id,
|
|
OffsetDateTime::now_utc(),
|
|
)
|
|
.await?;
|
|
return Ok(OnboardingEventResponse {
|
|
accepted: false,
|
|
onboarding: self
|
|
.map_onboarding_response(latest.projection, latest.import_context)
|
|
.await?,
|
|
});
|
|
}
|
|
if replay.is_some() {
|
|
return Err(ApiError::conflict_with_context(
|
|
"idempotency key was already used for another onboarding event",
|
|
json!({"error_code":"onboarding_idempotency_conflict","recovery":"use_original_event"}),
|
|
));
|
|
}
|
|
return Err(ApiError::conflict_with_context(
|
|
"onboarding state changed; reload before retrying",
|
|
json!({"error_code":"onboarding_stale_revision","recovery":"reload"}),
|
|
));
|
|
}
|
|
Err(RegistryError::InvalidExecutionRecord {
|
|
field: "product_event.idempotency_conflict",
|
|
}) => {
|
|
return Err(ApiError::conflict_with_context(
|
|
"idempotency key was already used for another onboarding event",
|
|
json!({"error_code":"onboarding_idempotency_conflict","recovery":"use_original_event"}),
|
|
));
|
|
}
|
|
Err(other) => return Err(other.into()),
|
|
};
|
|
Ok(OnboardingEventResponse {
|
|
accepted: outcome.accepted,
|
|
onboarding: self
|
|
.map_onboarding_response(
|
|
outcome.snapshot.projection,
|
|
outcome.snapshot.import_context,
|
|
)
|
|
.await?,
|
|
})
|
|
}
|
|
|
|
pub async fn reset_onboarding_selection(
|
|
&self,
|
|
workspace_id: &WorkspaceId,
|
|
expected_revision: i64,
|
|
) -> Result<ResetOnboardingSelectionResponse, ApiError> {
|
|
self.ensure_workspace_exists(workspace_id).await?;
|
|
let snapshot = self
|
|
.registry
|
|
.reset_onboarding_selection_snapshot(
|
|
workspace_id,
|
|
expected_revision,
|
|
OffsetDateTime::now_utc(),
|
|
)
|
|
.await
|
|
.map_err(|error| match error {
|
|
RegistryError::OnboardingStaleRevision => ApiError::conflict_with_context(
|
|
"onboarding state changed; reload before resetting the selection",
|
|
json!({"error_code":"onboarding_stale_revision","recovery":"reload"}),
|
|
),
|
|
other => ApiError::from(other),
|
|
})?;
|
|
Ok(ResetOnboardingSelectionResponse {
|
|
selection_reset: true,
|
|
onboarding: self
|
|
.map_onboarding_response(snapshot.projection, snapshot.import_context)
|
|
.await?,
|
|
})
|
|
}
|
|
|
|
pub async fn register_onboarding_import_context(
|
|
&self,
|
|
workspace_id: &WorkspaceId,
|
|
payload: RegisterOnboardingImportContextPayload,
|
|
) -> Result<RegisterOnboardingImportContextResponse, ApiError> {
|
|
self.ensure_workspace_exists(workspace_id).await?;
|
|
validate_application_identity(&payload.application_idempotency_key, &payload.plan_digest)?;
|
|
let snapshot = self
|
|
.registry
|
|
.register_onboarding_import_context_snapshot(RegisterOnboardingImportContextRequest {
|
|
workspace_id,
|
|
application_idempotency_key: &payload.application_idempotency_key,
|
|
plan_digest: &payload.plan_digest,
|
|
expected_revision: payload.expected_revision,
|
|
occurred_at: OffsetDateTime::now_utc(),
|
|
})
|
|
.await?;
|
|
Ok(RegisterOnboardingImportContextResponse {
|
|
registered: true,
|
|
onboarding: self
|
|
.map_onboarding_response(snapshot.projection, snapshot.import_context)
|
|
.await?,
|
|
})
|
|
}
|
|
|
|
pub async fn select_onboarding_import_draft(
|
|
&self,
|
|
workspace_id: &WorkspaceId,
|
|
payload: SelectOnboardingImportDraftPayload,
|
|
) -> Result<SelectOnboardingImportDraftResponse, ApiError> {
|
|
self.ensure_workspace_exists(workspace_id).await?;
|
|
validate_application_identity(&payload.application_idempotency_key, &payload.plan_digest)?;
|
|
if payload.operation_id.is_empty() || payload.operation_id.len() > 128 {
|
|
return Err(ApiError::validation(
|
|
"operation_id must contain 1..128 bytes",
|
|
));
|
|
}
|
|
if payload.operation_version == 0 {
|
|
return Err(ApiError::validation("operation_version must be positive"));
|
|
}
|
|
let snapshot = self
|
|
.registry
|
|
.select_onboarding_import_draft_snapshot(SelectOnboardingImportDraftRequest {
|
|
workspace_id,
|
|
application_idempotency_key: &payload.application_idempotency_key,
|
|
plan_digest: &payload.plan_digest,
|
|
operation_id: &OperationId::new(payload.operation_id),
|
|
operation_version: payload.operation_version,
|
|
expected_revision: payload.expected_revision,
|
|
occurred_at: OffsetDateTime::now_utc(),
|
|
})
|
|
.await?;
|
|
Ok(SelectOnboardingImportDraftResponse {
|
|
selected: true,
|
|
onboarding: self
|
|
.map_onboarding_response(snapshot.projection, snapshot.import_context)
|
|
.await?,
|
|
})
|
|
}
|
|
|
|
async fn map_onboarding_response(
|
|
&self,
|
|
projection: OnboardingProjection,
|
|
import_context: Option<OnboardingImportContext>,
|
|
) -> Result<OnboardingResponse, ApiError> {
|
|
let endpoint = if let Some(agent_id) = projection.agent_id.as_ref() {
|
|
let workspace = self.get_workspace(&projection.workspace_id).await?;
|
|
let agent = self
|
|
.registry
|
|
.get_agent_summary(&projection.workspace_id, agent_id)
|
|
.await?
|
|
.ok_or_else(|| ApiError::internal("onboarding agent disappeared"))?;
|
|
Some(self.public_agent_mcp_endpoint(&workspace.workspace.slug, &agent.slug))
|
|
} else {
|
|
None
|
|
};
|
|
let first_call = match (
|
|
projection.first_call_log_id.as_ref(),
|
|
projection.agent_id.as_ref(),
|
|
projection.platform_api_key_id.as_ref(),
|
|
projection.operation_id.as_ref(),
|
|
projection.operation_version,
|
|
projection.first_call_tool_name.as_ref(),
|
|
projection.first_call_at,
|
|
) {
|
|
(
|
|
Some(log_id),
|
|
Some(agent_id),
|
|
Some(key_id),
|
|
Some(operation_id),
|
|
Some(operation_version),
|
|
Some(tool_name),
|
|
Some(occurred_at),
|
|
) => Some(OnboardingFirstCallEvidence {
|
|
log_id: log_id.as_str().to_owned(),
|
|
agent_id: agent_id.as_str().to_owned(),
|
|
key_id: key_id.as_str().to_owned(),
|
|
operation_id: operation_id.as_str().to_owned(),
|
|
operation_version,
|
|
tool_name: tool_name.clone(),
|
|
occurred_at: format_timestamp(occurred_at),
|
|
request_id: projection.first_call_request_id.clone(),
|
|
trace_id: projection.first_call_trace_id.clone(),
|
|
}),
|
|
_ => None,
|
|
};
|
|
let first_incomplete = projection.steps.iter().position(|step| !step.completed);
|
|
let import_context = import_context.map(map_import_context);
|
|
Ok(OnboardingResponse {
|
|
schema_version: 1,
|
|
workspace_id: projection.workspace_id.as_str().to_owned(),
|
|
revision: projection.revision,
|
|
status: if projection.completed {
|
|
"complete".to_owned()
|
|
} else {
|
|
"in_progress".to_owned()
|
|
},
|
|
completed: projection.completed,
|
|
eligible_since: projection.eligible_since.map(format_timestamp),
|
|
steps: projection
|
|
.steps
|
|
.iter()
|
|
.enumerate()
|
|
.map(|(index, step)| {
|
|
let status = if step.completed {
|
|
"complete"
|
|
} else if projection.was_completed {
|
|
"regressed"
|
|
} else if Some(index) == first_incomplete {
|
|
"current"
|
|
} else {
|
|
"pending"
|
|
};
|
|
let reason_code = match status {
|
|
"complete" => "authoritative_evidence_present",
|
|
"regressed" => "authoritative_evidence_regressed",
|
|
"current" => "authoritative_evidence_missing",
|
|
_ => "prerequisite_incomplete",
|
|
};
|
|
OnboardingStepView {
|
|
id: step.id,
|
|
completed: step.completed,
|
|
status: status.to_owned(),
|
|
action_code: action_code(step.id).to_owned(),
|
|
reason_code: reason_code.to_owned(),
|
|
}
|
|
})
|
|
.collect(),
|
|
operation_id: projection.operation_id.map(|id| id.as_str().to_owned()),
|
|
operation_version: projection.operation_version,
|
|
agent_id: projection.agent_id.map(|id| id.as_str().to_owned()),
|
|
catalog_revision: projection.catalog_revision,
|
|
platform_api_key_id: projection
|
|
.platform_api_key_id
|
|
.map(|id| id.as_str().to_owned()),
|
|
mcp_endpoint: endpoint,
|
|
first_call,
|
|
import_context,
|
|
})
|
|
}
|
|
}
|
|
|
|
fn map_import_context(context: OnboardingImportContext) -> OnboardingImportContextView {
|
|
OnboardingImportContextView {
|
|
application_idempotency_key: context.application_idempotency_key,
|
|
plan_digest: context.plan_digest,
|
|
report: context.report,
|
|
choices: context
|
|
.choices
|
|
.into_iter()
|
|
.map(|choice| OnboardingImportChoiceView {
|
|
key: choice.key,
|
|
name: choice.name,
|
|
outcome: choice.outcome,
|
|
operation_id: choice.operation_id,
|
|
version: choice.version,
|
|
reason: choice.reason,
|
|
selectable: choice.selectable,
|
|
})
|
|
.collect(),
|
|
selected_operation_id: context
|
|
.selected_operation_id
|
|
.map(|id| id.as_str().to_owned()),
|
|
selected_operation_version: context.selected_operation_version,
|
|
drift: context.drift.map(|drift| OnboardingImportDriftView {
|
|
reason: drift.reason,
|
|
current_operation_version: drift.current_operation_version,
|
|
}),
|
|
}
|
|
}
|
|
|
|
fn validate_application_identity(
|
|
application_idempotency_key: &str,
|
|
plan_digest: &str,
|
|
) -> Result<(), ApiError> {
|
|
if application_idempotency_key.is_empty() || application_idempotency_key.len() > 128 {
|
|
return Err(ApiError::validation(
|
|
"application_idempotency_key must contain 1..128 bytes",
|
|
));
|
|
}
|
|
let valid_digest = plan_digest.len() == 64
|
|
&& plan_digest
|
|
.bytes()
|
|
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte));
|
|
if !valid_digest {
|
|
return Err(ApiError::validation(
|
|
"plan_digest must be 64 lowercase hex characters",
|
|
));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn action_code(step: OnboardingStepId) -> &'static str {
|
|
match step {
|
|
OnboardingStepId::Operation => "create_operation",
|
|
OnboardingStepId::Test => "test_operation",
|
|
OnboardingStepId::PublishOperation => "publish_operation",
|
|
OnboardingStepId::Agent => "publish_agent",
|
|
OnboardingStepId::Key => "create_mcp_key",
|
|
OnboardingStepId::McpConnection => "connect_mcp_client",
|
|
OnboardingStepId::FirstCall => "call_tool",
|
|
}
|
|
}
|
|
|
|
fn onboarding_event_not_allowed() -> ApiError {
|
|
ApiError::unprocessable_with_context(
|
|
"client cannot complete authoritative onboarding steps",
|
|
json!({"error_code":"onboarding_event_not_allowed"}),
|
|
)
|
|
}
|