Files
crank/apps/admin-api/src/routes/prompts.rs
T
bsodfather 54ce770682
CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s
feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
Recovery delivery of the accumulated, TL-accepted Epic 3 work that had never been
committed to Git (stories 3.6-3.17, see the crank board). Story 3.18 is not accepted
yet and is deliberately excluded: its logging surface, its capability registration,
its oracle projections and its tests are not part of this tree.

Accepted scope
- 3.6 typed static Resource Drafts; 3.7 publication and exact binding of static
  Resource Versions; 3.8 MCP discovery/read and revocation of static Resources;
- 3.9 Resource import/export in API and UI plus TLS dependency maintenance;
  3.10 REST-backed Resource templates; 3.11 shared REST read runtime and the MCP
  revision/capability foundation;
- 3.12 parameterised Prompt Drafts with preview; 3.13 Prompt publication and exact
  version binding to Agents; 3.14 MCP prompts; 3.15 Prompt import/export;
- 3.16 composite Prompts with published Resources (dependency content scan plus
  dynamic read through the accepted 3.11 runtime, admin preview and MCP prompts/get);
- 3.17 bounded MCP completion suggestions from typed published schemas and the
  resources/list admission fix for bound template publications.

Accepted evidence being reused (unchanged code paths)
- 3.16 candidate: core 7, admin-api 22, registry 4, mcp-server 4, UI 6; one final
  `just verify` run 1651 passed / 0 failed / 2 ignored.
- 3.17 candidate: full run 1672 passed / 0 failed / 2 ignored, QA targeted reruns and
  a real MCP Inspector 2.12.0 client smoke.

Delivery engineering in this commit
- CI: one event per change (feature branches are gated by their pull request, push
  runs only on main), story events run the changed packages, the full workspace suite
  stays the feature/release gate; no cache/sharding without a measured runner check.
- Release: the packaged archives, checksums and SBOM are now uploaded to the Gitea
  release entry of the tag instead of dying with the runner workspace.

Not included on purpose: Story 3.18 work, build caches, runtime databases, local
credentials and scratch evidence.

Refs: crank kanban t_e39d7263; baseline 1b6db09bd1.
2026-10-25 09:08:22 +00:00

215 lines
6.7 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
use axum::{
Extension, Json,
extract::{Path, Query, State, rejection::JsonRejection},
http::{HeaderMap, HeaderValue, StatusCode, header},
response::{IntoResponse, Response},
};
use crank_core::{WorkspaceId, ids::PromptId};
use serde::Deserialize;
use serde_json::Value;
use crate::{error::ApiError, request_context::RequestContext, state::AppState};
#[derive(Deserialize)]
pub struct WorkspacePath {
workspace_id: String,
}
#[derive(Deserialize)]
pub struct PromptPath {
workspace_id: String,
prompt_id: String,
}
#[derive(Deserialize)]
pub struct PromptVersionPath {
workspace_id: String,
prompt_id: String,
version: u32,
}
#[derive(Deserialize)]
pub struct PromptQuery {
version: Option<u32>,
}
pub async fn list_prompt_drafts(
Path(path): Path<WorkspacePath>,
State(state): State<AppState>,
) -> Result<Json<Value>, ApiError> {
Ok(Json(
state
.service
.list_prompt_drafts(&WorkspaceId::new(path.workspace_id))
.await?,
))
}
pub async fn create_prompt_draft(
Path(path): Path<WorkspacePath>,
State(state): State<AppState>,
Json(body): Json<Value>,
) -> Result<(StatusCode, Json<Value>), ApiError> {
let prompt = state
.service
.create_prompt_draft(&WorkspaceId::new(path.workspace_id), body)
.await?;
Ok((StatusCode::CREATED, Json(prompt)))
}
pub async fn get_prompt_draft(
Path(path): Path<PromptPath>,
Query(query): Query<PromptQuery>,
State(state): State<AppState>,
) -> Result<Json<Value>, ApiError> {
Ok(Json(
state
.service
.get_prompt_draft(
&WorkspaceId::new(path.workspace_id),
&PromptId::new(path.prompt_id),
query.version,
)
.await?,
))
}
pub async fn prompt_action(
Path(path): Path<PromptPath>,
State(state): State<AppState>,
Json(body): Json<Value>,
) -> Result<Json<Value>, ApiError> {
Ok(Json(
state
.service
.prompt_action(
&WorkspaceId::new(path.workspace_id),
&PromptId::new(path.prompt_id),
body,
)
.await?,
))
}
pub async fn update_prompt_draft(
Path(path): Path<PromptPath>,
State(state): State<AppState>,
Json(body): Json<Value>,
) -> Result<Json<Value>, ApiError> {
Ok(Json(
state
.service
.update_prompt_draft(
&WorkspaceId::new(path.workspace_id),
&PromptId::new(path.prompt_id),
body,
)
.await?,
))
}
pub async fn preview_prompt_draft(
Path(path): Path<PromptPath>,
State(state): State<AppState>,
Extension(request_context): Extension<RequestContext>,
Json(body): Json<Value>,
) -> Result<Json<Value>, ApiError> {
Ok(Json(
state
.service
.preview_prompt_draft(
&WorkspaceId::new(path.workspace_id),
&PromptId::new(path.prompt_id),
body,
&request_context.correlation,
)
.await?,
))
}
/// Story 3.15: экспорт текущего Draft. Ответ всегда JSON + `attachment` + `nosniff`,
/// поэтому переносимый definition никогда не рендерится как документ браузера.
pub async fn export_prompt_draft(
Path(path): Path<PromptPath>,
State(state): State<AppState>,
) -> Result<Response, ApiError> {
let (envelope, filename) = state
.service
.export_prompt_draft_envelope(
&WorkspaceId::new(path.workspace_id),
&PromptId::new(path.prompt_id),
)
.await?;
portable_response(&envelope, &filename)
}
/// Story 3.15: экспорт точной Published Version (immutable snapshot этой ревизии).
pub async fn export_prompt_version(
Path(path): Path<PromptVersionPath>,
State(state): State<AppState>,
) -> Result<Response, ApiError> {
let (envelope, filename) = state
.service
.export_published_prompt_envelope(
&WorkspaceId::new(path.workspace_id),
&PromptId::new(path.prompt_id),
path.version,
)
.await?;
portable_response(&envelope, &filename)
}
/// Story 3.15: импорт envelope как **нового** Draft текущего владельца (201 + item view).
///
/// Target workspace берётся только из URL, владелец — только из session; envelope не
/// может задать ни ownership, ни lifecycle, ни идентичность Prompt.
pub async fn import_prompt(
Path(path): Path<WorkspacePath>,
State(state): State<AppState>,
body: Result<Json<Value>, JsonRejection>,
) -> Result<Response, ApiError> {
let envelope = body.map_err(import_body_error)?;
let imported = state
.service
.import_prompt_envelope(&WorkspaceId::new(path.workspace_id), envelope.0)
.await?;
Ok((StatusCode::CREATED, Json(imported)).into_response())
}
fn portable_response(envelope: &Value, filename: &str) -> Result<Response, ApiError> {
let mut headers = HeaderMap::new();
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/json"),
);
headers.insert(
header::HeaderName::from_static("x-content-type-options"),
HeaderValue::from_static("nosniff"),
);
// Filename выведен из `name` (ASCII alnum/-/_) с фиксированным суффиксом: CR/LF и
// traversal структурно невозможны.
headers.insert(
header::CONTENT_DISPOSITION,
HeaderValue::from_str(&format!("attachment; filename=\"{filename}\""))
.map_err(|_| ApiError::internal("invalid prompt portability export filename"))?,
);
let body = serde_json::to_vec(envelope)
.map_err(|_| ApiError::internal("invalid prompt portability envelope"))?;
Ok((headers, body).into_response())
}
/// Отказ разбора тела импорта: не JSON — 400 стабильный `prompt_portability_envelope_invalid`,
/// а не generic framework rejection.
fn import_body_error(rejection: JsonRejection) -> ApiError {
if rejection.into_response().status() == StatusCode::PAYLOAD_TOO_LARGE {
ApiError::PayloadTooLarge {
message: "prompt portability import body is too large".to_owned(),
context: Some(serde_json::json!({
"error_code": "prompt_portability_envelope_invalid"
})),
}
} else {
ApiError::validation_with_context(
"prompt portability envelope is invalid",
serde_json::json!({ "error_code": "prompt_portability_envelope_invalid" }),
)
}
}